In golang is there a nice way of getting a slice of values from a map?

前端 未结 5 1935
小蘑菇
小蘑菇 2020-12-23 15:38

If I have a map m is there a better way of getting a slice of the values v then

package main
import (
  \"fmt\"
)

func main() {
    m := make(map[int]string         


        
5条回答
  •  梦毁少年i
    2020-12-23 16:23

    As far as I'm currently aware, go doesn't have a way method for concatenation of strings/bytes in to a resulting string without making at least /two/ copies.

    You currently have to grow a []byte since all string values are const, THEN you have to use the string builtin to have the language create a 'blessed' string object, which it will copy the buffer for since something somewhere could have a reference to the address backing the []byte.

    If a []byte is suitable then you can gain a very slight lead over the bytes.Join function by making one allocation and doing the copy calls your self.

    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)
    }
    

提交回复
热议问题