怪物奇妙物语

宇宙无敌超级美少男的怪物奇妙物语

首页 新随笔 联系 管理
  819 随笔 :: 0 文章 :: 2 评论 :: 16万 阅读

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   超级无敌美少男战士  阅读(4)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 清华大学推出第四讲使用 DeepSeek + DeepResearch 让科研像聊天一样简单!
· 推荐几款开源且免费的 .NET MAUI 组件库
· 实操Deepseek接入个人知识库
· 易语言 —— 开山篇
· Trae初体验
历史上的今天:
2024-01-18 code2markdown class
2024-01-18 dotnet 连接多个数据库
点击右上角即可分享
微信分享提示