TypeCast Definition Error

The below mentioned code shows error:
prog.go:16: cannot use *ptnew (type uint32) as type pa in assignment

The code is:
package main

import (
“fmt”
)

type pa uint32
type pt *uint32

func main() {

var panew pa		// Declares variable 'panew' of type uint32
newint := uint32(24) 	// Assigns the variable 'newint' of type uint32 (dynamically) a uint32 type value

var ptnew pt = &newint 	// Assigns address of 'newint' into 'ptnew' which is of type pt, alias for *uint32
panew = *ptnew

fmt.Println(panew)

}

However, when I change the line #16 to:
panew = pa(*ptnew)

it works fine.

Please suggest why?

Go does not have implicit type conversions, and pa is a different type than uint32.

1 Like

A named type (pa) and an unnamed type (uint32) are not the same types, so you cannot do the assignment without a conversion (go does not use the word cast, because there are no casts)

1 Like

The reason behind this is safety. As Jacob and Dave explained, an explicit conversion is necessary. This prevents a couple of programmer errors. Consider, for example, geospatial calculations. If you define two types, say,

type lat float64
type long float64

then the compiler warns you if you erroneously try to assign a latitude value to a longitude, or any plain float64 value to a lat or long type.

1 Like

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.