Go - Struct

Go - Struct

Introduction-Struct

struct

  1. user-defined data type.

  2. a structure that groups together data elements.

  3. provide a way to reference a series of grouped values through a single variable name.

  4. used when it makes sense to group or associate two or more data variables.

Declaring and Initializing a Struct

struct-declaration

  type struct {
    // list of fields
    }

    type Circle struct {
      x float64
      y float64
      r float64
    }
  type Student struct {
    name string
    rollNo int
    marks []int
    grades map[string] int

struct-initialize

  var 
    var s Student

main.go

  package main
  import "fmt"
  type Student struct {
    name string
    rollNo int
    marks []int
    grades map[string] int
  }
  func main() {
    var s Student
    fmt.Printf("%+v", s)
  }
  >>> go run main.go
  {name: rollNo:0 marks:[] grades:map[]}

Accessing Fields

  .

main.go

  package main
  import "fmt"
  type Circle struct {
    x int
    y int
    radius int
  }

  func main () {
    var c Circle
    c.x = 5
    c.y = 5
    c.radius = 5
    fmt.Printf("%+v \n", c)
    fmt.Printf("&+v \n", c.area)
  }
  >>> go run main.go
      c.area undefined (type Circle has no field or method area)

That's great if you have make till here you have covered basic of Golang Struct.

If you liked what you read, do follow and any feedback for further improvement will be highly appreciated!

Thank you and Happy Learning!👏