GitopsCentral

Structs in Golang

Filed under: golang — Tags: , , — shaik zillani @ 10:48 am

Struct is a collection of fields.

Syntax

type User struct {
      username string
      email string
      phone string
}

var u1 User

Initializing Structs

Struct can be initialized using new keyword which will initialize fields with 0or in below manner,

 user1 := User {username: "sam", email: "sam123@gmail.com", phone: "987654322"}

Using new keyword,

user1 := new(User)

Example

package main

import "fmt"

type User struct {
        username string
        email string
        phone string
}

func main() {
  user1 := User {username: "sam", email: "sam123@gmail.com", phone: "987654322"}
  fmt.Println(user1)
}

Output

{sam sam123@gmail.com 987654322}

© 2016–2025 GitOpsCentral | All Rights Reserved.