Constructors

There are no constructors in Go, but there are New() functions that act like factories initializing an object. You simply have to create a function named New() that returns your data type. Here is an example:

package mainimport "fmt"type Person struct {   Name string}func NewPerson() Person {   return Person{      Name: "Anonymous",   }}func main() {   p := NewPerson()   fmt.Println(p)} 

There are no deconstructors in Go, since everything is garbage collected and you do not manually destroy objects. Defer is the closest you can get by deferring a function call to perform some cleanup when the current function ends.

Get Security with Go now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.