繁体   English   中英

在 Go 中如何从地图中获取一个值?

[英]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))

这里暗示容量与长度相同。

去 1.18

您可以使用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)
}

从 1.18 开始,这是最好的方法: https ://stackoverflow.com/a/71635953/130427

1.18 之前

您可以使用此maps包:

go get https://github.com/drgrib/maps

那么你只需要打电话

values := maps.GetValuesIntString(m)

对于该常见的map组合,它是类型安全的。 您可以使用同一包中的mapper工具为任何其他类型的map generate其他类型安全的函数。

完全披露:我是这个包的创建者。 我创建它是因为我发现自己反复为map重写这些函数。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM