Created
April 28, 2025 15:13
-
-
Save Thedrogon/11d59e765e2dec6ccdc1b97abad3c400 to your computer and use it in GitHub Desktop.
Structs , Receivers , pointers in Golang
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
func main(){ | |
type Person struct { //its a defined struct | |
Name string | |
ID int | |
Address Address //types of a property can be itself a struct | |
Contact string | |
} | |
employee := Employeeinfo{ // This is an anonymous struct where along with type u actually initialise the data. | |
Name string | |
DOB date | |
Address Address | |
}{ | |
Name : "Roshan Sangu", | |
DOB : 22.05.2011, | |
Address : { | |
Address_name : "Amsterdam , Rosale lane " , | |
Address_type : "Work" , | |
}, | |
} | |
//We can pass structs as arguments in a function (a gotch! of go) | |
person_info := Person{ | |
Name : "Aloha Mendez ", | |
ID : 69 , | |
Address : { | |
Address_name : "Amsterdam , Rosale lane " , | |
Address_type : "Work" , | |
}, | |
Contact : "+031-667876686", | |
} | |
func modifyName(p Person){ | |
p.Name = "Melky Mendez " //intention is to change the name from aloha to melky which wont happen coz its not changin the actual variable rather changing it only within the function scope. | |
} | |
//To actually change the name we need to pass the pointer of that structured variable. | |
modifyName(&person_info) | |
func modifyName(p *Person){ | |
p.Name = "Melky" //now this is Actually CHANGING the name of the actual variable | |
} | |
//Receivers work in a different way which makes the function work only for that recived data | |
//eg:= | |
person_info.modifyName("Melky") // the functions becomes a attribute of that struct data | |
func (p *Person) modifyName(name string){ | |
p.Name = name | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment