-2

How could we call a function on hello as hello(0) below even though we have no function defined on hello?

package main
import "fmt"
type hello int32

func main() {
    x := hello(0)
    //converting int to int32
    fmt.Printf("Type : %T, Value: %v", x, x) //prints "Type : main.hello, Value: 0"
}
Jonathan Hall
  • 75,165
  • 16
  • 143
  • 189
Rajesh
  • 1,514
  • 2
  • 14
  • 15
  • 3
    see [Types](https://golang.org/ref/spec#Types): "*A type definition creates a new, distinct type with the same underlying type and operations as the given type, and binds an identifier to it.*" So since you can call `int32(0)`, you can also call `hello(0)`. – FObersteiner May 07 '21 at 11:53
  • 4
    Note that Go doesn't actually support typeasting. What you've demonstrated is a type conversion. – Jonathan Hall May 07 '21 at 11:56
  • Thanks for the comments. Well I see type "hello" has got the properties of int32. I was looking to find source code for the implementation of type int32 in golang source code. I found this https://github.com/golang/go/blob/5203357ebacf9f41ca5e194d953c164049172e96/src/builtin/builtin.go#L48. But even this doesn't have the actual implementation. Can someone direct me to the source code of int32 in golang? – Rajesh May 09 '21 at 07:58

1 Answers1

2

I highly suggest you to take a look at Types in Go.

Also, to set a variable to a custom type, you have to declare it manually.

In this case, it should be var x hello = 0

package main
import "fmt"

type hello int32

func main() {
    var x hello = 0 // converting int to hello
    fmt.Printf("Type : %T, Value: %v", x, x) // prints "Type: main.hello, Value: 0"
}

Now to convert a numeric type to hello type, use the hello(x) function (it's already built-in since you have the custom hello type)

Let's suppose you have the following code:

package main
import "fmt"

type hello int32

func main() {
    var x int = 0
    fmt.Printf("Type : %T, Value: %v", x, x) // prints "Type: int, Value: 0"
}

Here, we will convert x to hello type. To do it, just use hello(x).

package main
import "fmt"

type hello int32

func main() {
    var x int = 0
    y := hello(x) // converting 'x' to 'hello' type
    fmt.Printf("Type : %T, Value: %v", y, y) // prints "Type: main.hello, Value: 0"
}
Levan
  • 616
  • 6
  • 10