41

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)
peterSO
  • 158,998
  • 31
  • 281
  • 276
Senica Gonzalez
  • 7,996
  • 16
  • 66
  • 108

3 Answers3

67

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}
peterSO
  • 158,998
  • 31
  • 281
  • 276
7

Go does not have automatic constructors. Typically you create your own NewT() *T function which performs the necessary initialization. But it has to be called manually.

jimt
  • 25,324
  • 8
  • 70
  • 60
0

This is a Go struct initialize complete:

type Console struct {
    X int
    Y int
}

// Regular use case, create a function for easy create.
func NewConsole(x, y int) *Console {
    return &Console{X: x, Y: y}
}

// "Manually" create the object (Pointer version is same as non '&' version)
consoleP := &Console{X: 1, Y: 2}
console := Console{X: 1, Y: 2}

// Inline init
consoleInline :=  struct {
    X int
    Y int
}{
    X: 1,
    Y: 2,
}

pixeloverflow
  • 579
  • 1
  • 5
  • 23