为什么这个 Go 切片的长度是 4,为什么输出的切片中有空格?

huangapple go评论108阅读模式
英文:

why the length of this go slice is 4 and why the output has the space in slice?

问题

我是你的中文翻译助手,以下是你提供的代码的翻译:

我刚开始学习golang,在运行这段代码时,我得到的长度为4,想要理解为什么会这样?

package main

import "fmt"

type phone struct {
    model  string
    camera Camera
    ram    int
}

type Camera struct {
    lens      string
    aparature int
}

func main() {

    var m = make(map[string]phone)

    myphn1 := phone{model: "iphone", camera: Camera{"20", 4}, ram: 6}
    myphn2 := phone{model: "pixel", camera: Camera{"50", 2}, ram: 6}

    m["myphn1"] = myphn1
    m["myphn2"] = myphn2

    var k = make([]string, len(m))

    for key, _ := range m {
        k = append(k, key)
    }

    fmt.Println(k)
    fmt.Println(len(k))

}

我理解这段代码在创建时会增加2个大小,但在打印时会得到类似这样的结果,答案中的空间是为2个未分配的条目保留的吗?

[  myphn2 myphn1]
4

希望对你有帮助!

英文:

I am new to golang and while running this code snippet I am getting the len as 4, trying to understand why so ?

package main

import "fmt"

type phone struct {
	model  string
	camera Camera
	ram    int
}

type Camera struct {
	lens      string
	aparature int
}

func main() {

	var m = make(map[string]phone)

	myphn1 := phone{model: "iphone", camera: Camera{"20", 4}, ram: 6}
	myphn2 := phone{model: "pixel", camera: Camera{"50", 2}, ram: 6}

	m["myphn1"] = myphn1
	m["myphn2"] = myphn2

	var k = make([]string, len(m))

	for key, _ := range m {
		k = append(k, key)
	}

	fmt.Println(k)
	fmt.Println(len(k))

}

I understand this adds size of 2 while creating, but while printing it gives somelike this , is the space in answer for 2 unallocated entries ?

[  myphn2 myphn1]
4

答案1

得分: 3

这里创建了一个长度为2的切片(len(m)在这里是2):

var k = make([]string, len(m))

这里添加了两个元素,总共有4个:

for key, _ := range m {
    k = append(k, key)
}

如果你想要预分配一个切片,你需要提供一个长度为零和所需容量的参数:

var k = make([]string, 0, len(m))

这在Go之旅的示例中有详细说明。

英文:

This creates a slice of length 2 (len(m) is 2 here):

var k = make([]string, len(m))

This adds two elements to it, for a total of 4:

for key, _ := range m {
    k = append(k, key)
}

If you want to preallocate a slice, you need to provide a length of zero along with the desired capacity:

var k = make([]string, 0, len(m))

This is covered with examples in the Tour of Go.

答案2

得分: 2

你创建了一个长度为2的切片,并向其追加了两个元素,所以长度变为4。

你可能想要创建一个容量为2的切片:

var k = make([]string, 0, len(m))
英文:

You create a slice with length 2, and appended two more elements to it, so the length is 4.

what you probably want to do is to create a slice with capacity 2:

var k = make([]string,0,len(m))

huangapple
  • 本文由 发表于 2021年5月27日 01:20:13
  • 转载请务必保留本文链接:https://go.coder-hub.com/67709815.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定