Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

init function for structs

I realize that Go does not have classes but pushes the idea of structs instead.

Do structs have any sort of initialization function that can be called similar to a __construct() function of a class?

Example:

type Console struct {     X int     Y int }  func (c *Console) init() {     c.X = "5" }  // Here I want my init function to run var console Console  // or here if I used var console Console = new(Console) 
like image 898
Senica Gonzalez Avatar asked Nov 28 '11 23:11

Senica Gonzalez


People also ask

What is INIT in struct?

An initializer for a structure is a brace-enclosed comma-separated list of values, and for a union, a brace-enclosed single value. The initializer is preceded by an equal sign ( = ).

Can struct have init Swift?

In Swift, all structs come with a default initializer. This is called the memberwise initializer. A memberwise initializer assigns each property in the structure to self. This means you do not need to write an implementation for an initializer in your structure.

Can you initialize struct values?

You can also create and initialize a struct with a struct literal. An element list that contains keys does not need to have an element for each struct field. Omitted fields get the zero value for that field.

How do you initialize a struct in C?

Use Individual Assignment to Initialize a Struct in C Another method to initialize struct members is to declare a variable and then assign each member with its corresponding value separately.


1 Answers

Go doesn't have implicit constructors. You would likely write something like this.

package main  import "fmt"  type Console struct {     X int     Y int }  func NewConsole() *Console {     return &Console{X: 5} }  var console Console = *NewConsole()  func main() {     fmt.Println(console) } 

Output:

{5 0} 
like image 105
peterSO Avatar answered Sep 25 '22 23:09

peterSO