Avatar ·

Nil pointer dereference error in Go: causes and fix

Hello everyone! I'm a beginner in Go and encountered an error that has me stumped. I have a User struct, and I'm trying to write a function that prints the user's name. Here's my code: ```go package main import "fmt" type User struct { Name string Age int } func printUserName(u *User) { fmt.Println("User name is:", u.Name) } func main() { var user *User // Here I'm just declaring a pointer, but not initializing it printUserName(user) } ``` When I run this code, I get the error: `panic: runtime error: invalid memory address or nil pointer dereference`. I understand that it's somehow related to the user pointer being nil, but I don't fully understand how to fix it. In other languages, like C++ or Java, I could just before