[英]In Go how to get a slice of values from a map?
如果我有一张地图m
有没有比这更好的方法来获取值v
的一部分?
package main
import (
"fmt"
)
func main() {
m := make(map[int]string)
m[1] = "a"
m[2] = "b"
m[3] = "c"
m[4] = "d"
// Can this be done better?
v := make([]string, len(m), len(m))
idx := 0
for _, value := range m {
v[idx] = value
idx++
}
fmt.Println(v)
}
map
有内置功能吗? Go 包中是否有函数,或者这是唯一的方法?
作为 jimt 帖子的补充:
您也可以使用append
而不是显式地将值分配给它们的索引:
m := make(map[int]string)
m[1] = "a"
m[2] = "b"
m[3] = "c"
m[4] = "d"
v := make([]string, 0, len(m))
for _, value := range m {
v = append(v, value)
}
请注意,长度为零(尚无元素),但容量(分配的空间)使用m
的元素数进行初始化。 这样做是为了让append
不需要在每次 slice v
的容量用完时分配内存。
您还可以make
没有容量值的切片,并让append
为自己分配内存。
抱歉不行。 没有内置的方法可以做到这一点。
作为旁注,您可以在创建切片时省略容量参数:
v := make([]string, len(m))
这里暗示容量与长度相同。
您可以使用maps.Values
包中的golang.org/x/exp
。
Values 返回映射 m 的值。 这些值的顺序不确定。
func main() {
m := map[int]string{1: "a", 2: "b", 3: "c", 4: "d"}
v := maps.Values(m)
fmt.Println(v)
}
包exp
包括实验代码。 签名将来可能会或可能不会更改,并且可能会或可能不会被提升到标准库。
如果您不想依赖实验包,您可以轻松地自己实现它。 事实上,这段代码是从exp
包中复制粘贴的:
func Values[M ~map[K]V, K comparable, V any](m M) []V {
r := make([]V, 0, len(m))
for _, v := range m {
r = append(r, v)
}
return r
}
不一定更好,但更简洁的方法是定义切片长度和容量,如txs := make([]Tx, 0, len(txMap))
// Defines the Slice capacity to match the Map elements count
txs := make([]Tx, 0, len(txMap))
for _, tx := range txMap {
txs = append(txs, tx)
}
完整示例:
package main
import (
"github.com/davecgh/go-spew/spew"
)
type Tx struct {
from string
to string
value uint64
}
func main() {
// Extra touch pre-defining the Map length to avoid reallocation
txMap := make(map[string]Tx, 3)
txMap["tx1"] = Tx{"andrej", "babayaga", 10}
txMap["tx2"] = Tx{"andrej", "babayaga", 20}
txMap["tx3"] = Tx{"andrej", "babayaga", 30}
txSlice := getTXsAsSlice(txMap)
spew.Dump(txSlice)
}
func getTXsAsSlice(txMap map[string]Tx) []Tx {
// Defines the Slice capacity to match the Map elements count
txs := make([]Tx, 0, len(txMap))
for _, tx := range txMap {
txs = append(txs, tx)
}
return txs
}
简单的解决方案,但有很多陷阱。 阅读这篇博文了解更多详情: https ://web3.coach/golang-how-to-convert-map-to-slice-three-gotchas
据我目前所知,go 没有一种方法可以将字符串/字节连接到生成的字符串中,而无需制作至少 /two/ 副本。
您目前必须增加一个 []byte,因为所有字符串值都是 const,然后您必须使用内置的字符串让语言创建一个“祝福”字符串对象,它将复制缓冲区,因为某处可能有引用到支持 [] 字节的地址。
如果 []byte 是合适的,那么您可以在 bytes.Join 函数中获得非常小的领先优势,方法是进行一次分配并进行复制调用您自己。
package main
import (
"fmt"
)
func main() {
m := make(map[int]string)
m[1] = "a" ; m[2] = "b" ; m[3] = "c" ; m[4] = "d"
ip := 0
/* If the elements of m are not all of fixed length you must use a method like this;
* in that case also consider:
* bytes.Join() and/or
* strings.Join()
* They are likely preferable for maintainability over small performance change.
for _, v := range m {
ip += len(v)
}
*/
ip = len(m) * 1 // length of elements in m
r := make([]byte, ip, ip)
ip = 0
for _, v := range m {
ip += copy(r[ip:], v)
}
// r (return value) is currently a []byte, it mostly differs from 'string'
// in that it can be grown and has a different default fmt method.
fmt.Printf("%s\n", r)
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.