DEV Community


Is there a way to have custom typecasting in GoLang?

Calin Baenen
I'm a programmer born on October 30th, 2006. I love programming, it has, and always will be my passion.
・1 min read

I know there is typecasting in GoLang, such as:

type long int64;
type ulong uint64;

var l long = 39486;
var i16 = int64(l);
var ui16 = uint64(i16);

fmt.Println( string([]byte {100, 150, 125, 68, 66}) );
Enter fullscreen mode Exit fullscreen mode

But is there a way to add them to interface/struct types?

type IJType interface {/* ... */}

type JByte struct {/* Implements IJType */}
Enter fullscreen mode Exit fullscreen mode

Is there a way I could make a constructor, like in the following?

var j JByte = JByte(255 /*byte*/); // -> JByte(byte) -> JByte {/* ... */}
byte(j); // 255.
Enter fullscreen mode Exit fullscreen mode

Discussion (1)

baenencalin profile image
Calin Baenen Author

I know I can make a function called ConstructJByte, NewJByte, etc... But I want to avoid that, I want the literal typecasting that Go has. (Unless those are just functions in disguise, with the same name as the type (somehow).)