关于在 Go 上使用等号和地图的说明

为什么map在 Go上有不同的行为?


Go 中的所有类型都是按值复制的:string, intxx, uintxx, floatxx, struct, [...]array,[]slice除了map[key]value


package main


import "fmt"

type test1 map[string]int


func (t test1) DoSomething() { // doesn't need to use pointer

   t["yay"] = 1

}


type test2 []int


func (t* test2) DoSomething() { // must use pointer so changes would effect

    *t = append(*t,1)

}


type test3 struct{

    a string

    b int

}


func (t* test3) DoSomething() { // must use pointer so changes would effect

    t.a = "aaa"

    t.b = 123

}


func main() {

 t1 := test1{}

 u1 := t1

 u1.DoSomething()

 fmt.Println("u1",u1)

 fmt.Println("t1",t1)


 t2 := test2{}

 u2 := t2

 u2.DoSomething()

 fmt.Println("u2",u2)

 fmt.Println("t2",t2)


 t3 := test3{}

 u3 := t3

 u3.DoSomething()

 fmt.Println("u3",u3)

 fmt.Println("t3",t3)

}

并且将变量作为函数的参数/参数传递等于赋值 :=


package main


import "fmt"

type test1 map[string]int


func DoSomething1(t test1)  { // doesn't need to use pointer

   t["yay"] = 1

}


type test2 []int


func DoSomething2(t *test2) { // must use pointer so changes would effect

    *t = append(*t,1)

}


type test3 struct{

    a string

    b int

}


func DoSomething3(t *test3) { // must use pointer so changes would effect

    t.a = "aaa"

    t.b = 123

}


func main() {

 t1 := test1{}

 DoSomething1(t1)

 fmt.Println("t1",t1)


 t2 := test2{}

 DoSomething2(&t2)

 fmt.Println("t2",t2)


 t3 := test3{}

 DoSomething3(&t3)

 fmt.Println("t3",t3)

}


慕哥6287543
浏览 232回答 1
1回答

精慕HU

映射值是指针。其他一些类型(切片、字符串、通道、函数)类似地用指针实现。有趣的是,链接的常见问题解答条目说,早期,映射和通道在语法上是指针,不可能声明或使用非指针实例。...最终我们决定指针和值的严格分离使语言更难使用。“Go 按值传递”意味着作为常规函数 args 传递的变量不会被调用的函数修改。这不会改变某些内置类型可以包含指针(就像您自己的结构可以)。Python 是类似的:f(x)不会改变x传递给它的整数,但它可以附加到列表中,x因为 Python 列表是在内部使用指针实现的。相比之下,C++ 具有实际可用的引用传递:f(x)可以更改调用者的int xiff声明为具有引用参数 ( void f(int& x))。(我还在另一个问题的回答中写了一些关于指针与 Go中的值的一般信息,如果有帮助的话。)
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Go