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)
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}
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.
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,
}