This content originally appeared on Level Up Coding - Medium and was authored by Amit Kumar Manjhi
What are Structures?
- A structure or struct is a user-defined type to store a collection of different fields into a single field.
- Any real-world entity which has some set of properties/fields can be represented as a struct.
- For Example, an address has a name, street, city, state, pincode. It makes sense to group these three properties into a single structure.
How to Declare Structure?
type Address struct {
name string
street string
city string
state string
pincode int
}
OR
type Address struct {
name ,street ,city , state string
pincode int
}
To Define a Structure
var a Address
To Initialize a variable of a struct type
var a = Address{"Amit","Baner","Pune","Maharashtra",411045}
Note:
- Always pass the field values in the same order in which they are declared in which they are declared in the struct.
- Go also supports the name:value syntax for initializing a struct.
var a =Address{Name:"Vikas",street:"RamNagar",state:"Bihar",pincode:841406}
How to access fields of a struct?
- To access individual fields of a struct, use dot(.) operator
fmt.println("Name is:",a.name)
fmt.println("city is",a.city)
Thank you for reading :)
Reference : https://gobyexample.com/structs
Structures in GoLang was originally published in Level Up Coding on Medium, where people are continuing the conversation by highlighting and responding to this story.
This content originally appeared on Level Up Coding - Medium and was authored by Amit Kumar Manjhi
Amit Kumar Manjhi | Sciencx (2023-02-03T16:12:59+00:00) Structures in GoLang. Retrieved from https://www.scien.cx/2023/02/03/structures-in-golang/
Please log in to upload a file.
There are no updates yet.
Click the Upload button above to add an update.