Struct method aka Reciever function in Go
·162 words·1 min
go
reciever-func
struct-method
Table of Contents
Object Oriented Programming is a little different in Go. Instead of class
, Go has struct
which is like an object.
Create a
struct
>Create a struct
#
First you create a struct
object like this:
|
|
Declaring struct method>
Declaring struct method #
Then, you pass the struct
in a function like this:
|
|
Finally, calling the method using the struct>
Finally, calling the method using the struct #
Then you can call the function using the struct
as a reciever like this:
func main() {
p = Person{}
fmt.Println(p) // output: { 0}
p.addInfo("Wai Yan", 27)
fmt.Println(p) // output: {Wai Yan 27}
}
Why use reciever function?>
Why use reciever function? #
The function can only be called using dot operator with p
struct which is in a way an object.