Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What (exactly) does the type keyword do in go?

Tags:

I've been reading A Tour of Go to learn Go-Lang and so far it's going good.

I'm currently on the Struct Fields Lesson and here is the sample code from the right hand side:

package main  import "fmt"  type Vertex struct {   X int   Y int }  func main() {   v := Vertex{1, 2}   v.X = 4   fmt.Println(v.X) } 

Take a look at line 3:

type Vertex struct { 

What I don't understand this, what does the type keyword do and why is it there?

like image 317
LogicalBranch Avatar asked Dec 09 '18 06:12

LogicalBranch


People also ask

What is the use of type keyword?

In typescript the type keyword defines an alias to a type. We can also use the type keyword to define user defined types.

What is type keyword?

Type Keyword. The type keyword defines an alias to a type. type str = string; let cheese: str = 'gorgonzola'; let cake: str = 10; // Type 'number' is not assignable to type 'string'

How do you declare type in Golang?

Each data field in a struct is declared with a known type, which could be a built-in type or another user-defined type. Structs are the only way to create concrete user-defined types in Golang. Struct types are declared by composing a fixed set of unique fields.


1 Answers

The type keyword is there to create a new type. This is called type definition. The new type (in your case, Vertex) will have the same structure as the underlying type (the struct with X and Y). That line is basically saying "create a type called Vertex based on a struct of X int and Y int".

Don't confuse type definition with type aliasing. When you declare a new type, you are not just giving it a new name - it will be considered a distinct type. Take a look at type identity for more information on the subject.

like image 183
hscasn Avatar answered Oct 06 '22 00:10

hscasn