Skip to main content

Command Palette

Search for a command to run...

Creating Your Own Type

Updated
2 min readView as Markdown
Creating Your Own Type
S
DevRel at StackGen | Formerly at Deepfence ,Tenable , Accurics | AWS Community Builder also Docker Community Award Winner at Dockercon2020 | CyberSecurity Innovator of Year 2023 award by Bsides Bangalore | Docker/HashiCorp Meetup Organiser Bangalore & Co-Author of Learn Lightweight Kubernetes with k3s (2019) , Packt Publication & also run Non Profit CloudNativeFolks / CloudSecCorner Community To Empower Free Education reach out me twitterhttps://twitter.com/sangamtwts or just follow on GitHub -> https://github.com/sangam14 for Valuable Resources

Some people say, "Go is all about 'type.'" Go is a static programming language, and at the heart of a static programming language is that once you declare that a variable is of a certain type, that's static; it doesn't change.

Let's try creating our own type in the Go playground.

package main

import (
    "fmt"
)

var a int
type hotdog int
var b hotdog

func main() {
    a = 42
    b = 43
    fmt.Println(a)
    fmt.Printf("%T\n", a)
    fmt.Println(b)
    fmt.Printf("%T\n", b)
}

This returns:

42
int
43
main.hotdog

So we can see that the value of a is 42 and it is of type int, and the value of b is 43 and it is of type hotdog from the package main.

We created a type hotdog with the line type hotdog int, we declared a variable of type hotdog with var b hotdog, we assigned a value to the variable with b = 43

Go is a static programming language, so if I want to now do something like assign the value of b to a, with a = b the compiler will complain. We cannot take the value of something of type hotdog and assign it to something that is of type int.

package main

import (
    "fmt"
)

var a int
type hotdog int
var b hotdog

func main() {
    a = 42
    b = a  // we cannot assign the value of a type int to a type hotdog
    fmt.Println(a)
    fmt.Printf("%T\n", a)
    fmt.Println(b)
    fmt.Printf("%T\n", b)
}

returns tmp/sandbox982815840/main.go:13: cannot use a (type int) as type hotdog in assignment

12 views

More from this blog

C

CloudNativeFolks Community

140 posts

CloudNativeFolks is non profit community that empower and educate about cloud native technology !