Struct Instantiation using new keyword
An instance of a struct can also be created with the new keyword. It is then possible to assign data values to the data fields using dot notation.
Example
package main
import "fmt"
type rectangle struct {
length int
breadth int
color string
}
func main() {
rect1 := new(rectangle) // rect1 is a pointer to an instance of rectangle
rect1.length = 10
rect1.breadth = 20
rect1.color = "Green"
fmt.Println(rect1)
var rect2 = new(rectangle) // rect2 is an instance of rectangle
rect2.length = 10
rect2.color = "Red"
fmt.Println(rect2)
}
Most Helpful This Week
How do you handle HTTP client server logging in Go?
Multiple-value <function> in single-value context error in Golang
Find Type of Struct in Go Programming Language
Golang program to demonstrates how to encode map data into a JSON string.
Program in Go language to print Floyd's Triangle
What is Struct