In the above tutorial, we have seen that we have created a Structure of type student.
type student struct { name string roll int age int }
Now, a student speaks. And that's one of the behaviour of a student. And a behaviour can be represented by a function.
func speak() { fmt.Println("...") }
So, can we put the above 'speak()' Function inside the Structure declaration.
Well! Unfortunately, we can't. As Go makes us do it a little differently.
Let us see in the below example.
package main import "fmt" type student struct { name string roll int age int } func (s student) speak() { fmt.Println("My name is",s.name,", my age is",s.age,"and roll number is",s.roll) } func main() { student1 := student{name: "John", roll: 65, age: 10 } student1.speak() student2 := student{name: "Rakhi", roll: 50, age: 8 } student2.speak() }
So, in the above code, we have defined the 'speak()' Function as promised.
func (s student) speak() { fmt.Println("My name is",s.name,", my age is",s.age,"and roll number is",s.roll) }
But, don't you think, the 'speak()' Function looks a little different from a normal Function?
Well! Just after the 'func' keyword, there is a Structure type variable 's student'. That is not present in a normal function declaration.
And, the Structure type variable 's student' is what binds the function to the Structure 'student'.
In other words, the 'speak()' Function is a part of the Structure 'student' now.
Even though 'speak()' Function is declared outside the Structure 'student', still it is a part of it.
So, in the 'main()' Function, we have assigned the values to the 'student' type variable 'student1'.
Now since, the 'speak()' Function is a part of the 'student' type variable 'student1'. We have called the 'speak()' Function from 'student1'.
And the 'speak()' Function is called.
func (s student) speak() { fmt.Println("My name is",s.name,", my age is",s.age,"and roll number is",s.roll) }
Now since, 'speak()' Function is called from 'student1', 's student' of speak would refer to the object 'student1'.
In other words, 's' would be referring to the values of 'student1'.
And the print statement,
Would be printing the contents of 'student1'.
And exactly in the same way, the value of 'student2' is printed.