岛屿可以找到海
岛屿可以找到海

golang结构体自动解引用

package main

import "fmt"

type Config struct {
	IP   string
	Port int
}

func main() {
	c := Config{}
	Mytest(&c)
	fmt.Println(c.IP, c.Port)
	s := new(string)
	Mytest2(s)
	fmt.Println(*s)
}

func Mytest(c *Config) {
	c.IP = "127.0.0.1" // (*c).IP = "127.0.0.1"
	c.Port = 8080
}

func Mytest2(s *string) {
	*s = "aaaaa"
}

上述这段代码为什么Mytest2的参数赋值需要解引用,而Mytest不需要呢?

答:因为结构体会隐式的自动解引用,当然你也可以显示的方法来手动解除引用也是可以的,除了结构体以外剩下的数据类型都需要手动解除引用。







岛屿可以找到海

golang结构体自动解引用
package main import "fmt" type Config struct { IP string Port int } func main() { c := Config{} Mytest(&c) fmt.Println(c.IP, c.Port) s := new(string) Mytest2(…
扫描二维码继续阅读
2025-03-22