Common Go Pitfalls Every PHP Developer Should Avoid
A former PHP developer shares six typical Go programming mistakes—incorrect function syntax, map initialization, JSON struct export, slice mutation in loops, array versus slice semantics, and variable shadowing—along with corrected examples and explanations to help newcomers write idiomatic Go code.
After five years of PHP development, the author transitioned to Go and identified several recurring mistakes that PHP developers often encounter when writing Go code. This article lists six common pitfalls and provides corrected examples.
1. Function Definition Syntax
Problem: Placing the opening brace on a new line after the function name causes a syntax error.
func main(){
fmt.Println("php是世界上最好的语言")
}2. Map Definition and Initialization
Problem: Declaring a map variable without allocating memory leads to a runtime panic.
func main(){
m := make(map[string]string, 2)
m["php"] = "世界上最好的语言"
m["go"] = "世界上最好的语言"
fmt.Println(m)
}3. JSON Struct Export
Problem: Struct fields are unexported (lower‑case), so json.Marshal produces empty output.
type Student struct {
Id int
Name string
Score int
}
func main(){
s := Student{1, "小明", 99}
jsonS, _ := json.Marshal(s)
fmt.Println(string(jsonS))
}4. Modifying Elements Inside a Loop
Problem: Using the value variable from range does not modify the underlying slice.
func main(){
data := []int{1, 2, 3}
for i := range data {
data[i] += 1
}
fmt.Println(data)
}5. Array vs. Slice Parameter Passing
Problem: Arrays are passed by value, so changes inside a function do not affect the original array.
func change(data []int){
data[0] = 4
}
func main(){
data := []int{1, 2}
change(data)
fmt.Println(data) // prints [4 2]
}6. Variable Shadowing with :=
Problem: Using := inside an if block creates a new variable that does not affect the outer one.
func main(){
flag := 1
if true {
flag = 2
flag++
}
fmt.Println(flag) // prints 3
}These examples illustrate typical beginner errors when moving from PHP to Go and demonstrate the idiomatic ways to write correct Go code.
Link: https://www.cnblogs.com/lmz-blogs/p/16352023.html
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
Go Development Architecture Practice
Daily sharing of Golang-related technical articles, practical resources, language news, tutorials, real-world projects, and more. Looking forward to growing together. Let's go!
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
