In Go it is valid to create a type:
type Num int
but how can one then initialize that type? make(Num, 2) does not seem to work.
2 ways to create and initialize a new structThe new keyword can be used to create a new struct. It returns a pointer to the newly created struct. 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.
The declaration starts with the keyword type, then a name for the new struct, and finally the keyword struct. Within the curly brackets, a series of data fields are specified with a name and a type.
Go is a statically typed language, which means types of variables must be known at compile time, and you can't change their type at runtime.
The main purpose of the init() function is to initialize the global variables that cannot be initialized in the global context. Example: // Go program to illustrate the. // concept of init() function. // Declaration of the main package.
Initialize the type as you would initialize the underlying type. In your example, the underlying type is an int
. For example,
package main
import (
"fmt"
)
type Num int
func main() {
var m Num = 7
n := Num(42)
fmt.Println(m, n)
}
Output: 7 42
The built-in function make takes a type T, which must be a slice, map or channel type.
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