Doubt on struct initialization

I am defining the struct type and just assigning a variable to the type like below :

package main

import (
	"fmt"
)

type Student struct {
	
	rollNumber int
	Name       string
	subject    string
}

var student Student

func main() {

	student.Name = "siddhanta"
	fmt.Println(student.Name)

}

It should give an error as student variable is not initialized yet.
But it is giving correct output as siddhanta.

my question is go initialized the student variable to empty struct like student = Student{} implicitly ?

Yes. Every variable in Go is implicitly assigned the zero value, if it’s not explicitly initialized to some other value.

1 Like

Thank you @calmh

@calmh but this student variable is a struct type not a primitive type variable like int or string.
then how is it getting initialize implicitly to zero?
So, we don’t have to initialize the empty struct ever in go?

As the linked spec says, the initialization is recursive. All members of the struct get the zero value for their type. You do not need to explicitly initialize a struct to anything.

In fact, it is considered best practice to make the zero value of the struct useful and workable without any initialization. Take for example a bytes.Buffer:

var buf bytes.Buffer
fmt.Fprintln(&buf, "hello")

That works and is perfectly fine.

1 Like

Now, my doubt is perfectly cleared :smile:

1 Like

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.