![]() It is possible to create structs with fields that contain only a type without the field name. We have used emp8.firstName to access the firstName field in the above program and this program also outputs, First Name: Sam package mainįmt.Println("First Name:", emp8.firstName) The Go language gives us the option to use emp8.firstName instead of the explicit dereference (*emp8).firstName to access the firstName field. (*emp8).firstName is the syntax to access the firstName field of the emp8 struct. package mainįmt.Println("First Name:", (*emp8).firstName)Įmp8 in the above program is a pointer to the Employee struct. It is also possible to create pointers to a struct. Hence age and salary are assigned their zero values. no 16 and 17, firstName and lastName are initialized whereas age and salary are not. package mainįmt.Println("First Name:", emp5.firstName) In this case, the ignored fields are assigned zero values. It is also possible to specify values for some fields and ignore the rest. Hence firstName and lastName are assigned the zero values of string which is an empty string "" and age, salary are assigned the zero values of int which is 0. The above program defines emp4 but it is not initialized with any value. package mainįmt.Println("First Name:", emp4.firstName) ![]() ![]() When a struct is defined and it is not explicitly initialized with any value, the fields of the struct are assigned their zero values by default. package mainįmt.Println("First Name:", emp6.firstName)įmt.Printf("New Salary: $%d", emp6.salary)Įmp6.firstName in the above program accesses the firstName field of the emp6 struct. ![]() operator is used to access the individual fields of a struct. It makes sense to group these three properties into a single struct named Employee. It can be used in places where it makes sense to group the data into a single unit rather than having each of them as separate values.įor instance, an employee has a firstName, lastName and age. What is a struct?Ī struct is a user-defined type that represents a collection of fields. ![]()
0 Comments
Leave a Reply. |
AuthorWrite something about yourself. No need to be fancy, just an overview. ArchivesCategories |