Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to set default values in Go structs

There are multiple answers/techniques to the below question:

  1. How to set default values to golang structs?
  2. How to initialize structs in golang

I have a couple of answers but further discussion is required.

like image 868
Prateek Avatar asked May 10 '16 10:05

Prateek


People also ask

How do you define struct values in Golang?

Defining a struct typeThe type keyword introduces a new type. It is followed by the name of the type ( Person ) and the keyword struct to indicate that we're defining a struct . The struct contains a list of fields inside the curly braces. Each field has a name and a type.

What is the default value of string in Golang?

Default Value for Strings in Go The default or zero value for strings in the Go programming language is an empty string (i.e "").

What is the zero value of a struct in Golang?

A zero value struct is simply a struct variable where each key's value is set to their respective zero value. This article is part of the Structs in Go series. We can create a zero value struct using the var statement to initialize our struct variable.

Can go structs have functions?

Yes, there is a clear answer: C++ struct can have member functions.


1 Answers

One possible idea is to write separate constructor function

//Something is the structure we work with type Something struct {      Text string       DefaultText string  }  // NewSomething create new instance of Something func NewSomething(text string) Something {    something := Something{}    something.Text = text    something.DefaultText = "default text"    return something } 
like image 81
vodolaz095 Avatar answered Sep 20 '22 10:09

vodolaz095