怪奇物语

怪奇物语

首页 新随笔 联系 管理

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.

}


posted on 2025-01-18 08:00  超级无敌美少男战士  阅读(20)  评论(0)    收藏  举报