Menu

Go Struct Copying and Pointer Semantics Cause Unexpected `true false` Output for Java/Rust Developers
📰

Go Struct Copying and Pointer Semantics Cause Unexpected `true false` Output for Java/Rust Developers

DEV Community: go·Viktor Logvinov·17 days ago
#K6RCx8WY
#devtogo#devto#dev#struct#self
Reading 0:00
15s threshold

Introduction

Developers transitioning from Java or Rust to Go often encounter puzzling behaviors rooted in Go's unique handling of struct copying and pointer semantics . A seemingly simple program can produce unexpected outputs, such as true false , leaving developers scratching their heads. This phenomenon is not a bug but a direct consequence of Go's design choices, which prioritize simplicity and performance over implicit behavior. Understanding these nuances is critical, as they can lead to subtle bugs , inefficiencies , and maintainability issues if overlooked.

Consider the following Go puzzler, which encapsulates the issue:

package mainimport "fmt" type SelfReference struct { self * SelfReference } func make () SelfReference { s := SelfReference {} s . self = & s return s } func main () { s := make () fmt . Println ( s == * s . self , & s == s . self )}

Enter fullscreen mode

Exit fullscreen mode

The output, true false , arises from Go's value semantics for structs.…

Continue reading — create a free account

Join HashtagPLUS to read full articles, follow hashtags, vote, and join the conversation.