Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

语法找错题 最后一道解答错误 #54

Open
jxy90 opened this issue Dec 8, 2021 · 0 comments
Open

语法找错题 最后一道解答错误 #54

jxy90 opened this issue Dec 8, 2021 · 0 comments

Comments

@jxy90
Copy link

jxy90 commented Dec 8, 2021

https://github.com/lifei6671/interview-go/blob/master/question/q014.md

下面代码写法有什么问题?

package main
import (
    "fmt"
)
type Student struct {
    Age int
}
func main() {
    kv := map[string]Student{"menglu": {Age: 21}}
    kv["menglu"].Age = 22
    s := []Student{{Age: 21}}
    s[0].Age = 22
    fmt.Println(kv, s)
}

-golang中的map 通过key获取到的实际上是两个值,第一个是获取到的值,第二个是是否存在该key。因此不能直接通过key来赋值对象-(错误解答)

是因为map中保存的是值类型 kv["menglu"] 操作是拿到map中的拷贝
如果换成 kv := map[string]*Student{"menglu": {Age: 21}} 使用指针就不会有问题

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant