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)
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 ( = ).
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.
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.
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.
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}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With