How to define type without operations allowed on the underlying type?

52 views Asked by At

If I define a type definition

type X int64

Why is it that I can then do

var x X = 123
x = x + 1

The x behaves as if it was the underlying int64, which I don't want. Or that it allows operations on the underlying type to be performed on this new type?

One of the reasons I'd define a new type is to hide the underlying type and define my own operations on it.

1

There are 1 answers

0
Hymns For Disco On

Creating a new defined type will dissociate any methods on the underlying type, but it does not dissociate functionality with operators such as + - / *.

A defined type may have methods associated with it. It does not inherit any methods bound to the given type

You should base your type on an underlying type with the desirable operators. For example, if you don't want to have arithmetic operators, you can derive from a struct.

If your type still needs the arithmetic capabilities of an int64 for internal reasons, you can hide it as an un-exported field in the struct. For example:

type X struct {
   number int64
}