golang 指针传递和值传递
package main
import "fmt"
type MyStruct struct {
Value string
}
// 值传递
// ModifyStruct takes a MyStruct by value and tries to modify it.
func ModifyStruct(s MyStruct) {
s.Value = "Modified"
}
// 指针传递
// ModifyStructPtr takes a pointer to MyStruct and modifies the original.
func ModifyStructPtr(s *MyStruct) {
s.Value = "Modified"
}
// 值传递
func ModifyStructPtrV2(s MyStruct) {
s.Value = "Modified"
}
func main() {
// Using value passing
s1 := MyStruct{Value: "Original"}
ModifyStruct(s1)
fmt.Println(s1.Value) // Output will be "Original" because s1 was not modified.
// Using pointer passing
s2 := &MyStruct{Value: "Original"}
ModifyStructPtr(s2)
fmt.Println((*s2).Value) // Output will be "Modified" because s2 was modified.
s3 := &MyStruct{Value: "Original"}
ModifyStructPtrV2(*s3)
fmt.Println((*s3).Value) // Output will be "Orginal" because s3 was not modified.
}
标签:golang,s3,s2,fmt,MyStruct,Value,传递,指针
From: https://www.cnblogs.com/zhuoss/p/18676468