Go Structs Example

Go’s structs are typed collections of fields. They’re useful for grouping data together to form records.

Go struct definition

A struct is defined with the type keyword:

type User struct {
    firstName       string
    lastName string
    email        string
}

Go Structs Example

The following is a Go struct simple example.


package main

import "fmt"

type User struct {
    firstName    string
    lastName     string
    email        string
}

func main() {

    u := User{"John", "Cena", "john@gmail.com"}

     // print user structure
     fmt.Println(u)

     // The struct fields are accessed with the dot operator.
     fmt.Println(u.firstName)
     fmt.Println(u.lastName)
     fmt.Println(u.email)
}

Output:

{John Cena john@gmail.com}
John
Cena
john@gmail.com

Free Spring Boot Tutorial - 5 Hours Full Course


Watch this course on YouTube at Spring Boot Tutorial | Fee 5 Hours Full Course

Comments