Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Initialize custom int type in Go

Tags:

types

go

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.

like image 390
mgamer Avatar asked May 18 '11 21:05

mgamer


People also ask

How do you initialize a structure in go?

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.

How do you declare a type in Golang?

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.

How do I change variable type in Golang?

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.

What is init go?

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.


1 Answers

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.

like image 99
peterSO Avatar answered Sep 30 '22 14:09

peterSO