init function for structs

Senica Gonzalez picture Senica Gonzalez · Nov 29, 2011 · Viewed 25.9k times · Source

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)

Answer

peterSO picture peterSO · Nov 29, 2011

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}