Define a primitive data type: Difference between revisions

Added Go
(Removed {{omit from|Go}} template as this task can in fact be completed in a reasonable fashion in the language.)
(Added Go)
Line 724:
<pre>
i = 10 j = 3 k = 4 j + 6 = 9 j + k = 7
</pre>
 
=={{header|Go}}==
{{trans|Kotlin}}
 
 
Creating a type that behaves like an integer but yet is distinct from it can be done in Go subject to the following constraints:
 
1. An instance of the new type needs to be created via a factory function (Go doesn't have constructors or user defined literals) to ensure it lies between 1 and 10. If an attempt is made to create an instance outside these limits, the value is adjusted so that it is just within them.
 
2. Go doesn't support operator overloading and so methods need to be defined for the standard operations on integers. As in the case of the Kotlin entry, only the basic arithmetic operations and the increment and decrement operations have been catered for below.
<lang go>package main
 
import "fmt"
 
type TinyInt int
 
func NewTinyInt(i int) TinyInt {
if i < 1 {
i = 1
} else if i > 10 {
i = 10
}
return TinyInt(i)
}
 
func (t1 TinyInt) Add(t2 TinyInt) TinyInt {
return NewTinyInt(int(t1) + int(t2))
}
 
func (t1 TinyInt) Sub(t2 TinyInt) TinyInt {
return NewTinyInt(int(t1) - int(t2))
}
 
func (t1 TinyInt) Mul(t2 TinyInt) TinyInt {
return NewTinyInt(int(t1) * int(t2))
}
 
func (t1 TinyInt) Div(t2 TinyInt) TinyInt {
return NewTinyInt(int(t1) / int(t2))
}
 
func (t1 TinyInt) Rem(t2 TinyInt) TinyInt {
return NewTinyInt(int(t1) % int(t2))
}
 
func (t TinyInt) Inc() TinyInt {
return t.Add(TinyInt(1))
}
 
func (t TinyInt) Dec() TinyInt {
return t.Sub(TinyInt(1))
}
 
func main() {
t1 := NewTinyInt(6)
t2 := NewTinyInt(3)
fmt.Println("t1 =", t1)
fmt.Println("t2 =", t2)
fmt.Println("t1 + t2 =", t1.Add(t2))
fmt.Println("t1 - t2 =", t1.Sub(t2))
fmt.Println("t1 * t2 =", t1.Mul(t2))
fmt.Println("t1 / t2 =", t1.Div(t2))
fmt.Println("t1 % t2 =", t1.Rem(t2))
fmt.Println("t1 + 1 =", t1.Inc())
fmt.Println("t1 - 1 =", t1.Dec())
}</lang>
 
{{out}}
<pre>
t1 = 6
t2 = 3
t1 + t2 = 9
t1 - t2 = 3
t1 * t2 = 10
t1 / t2 = 2
t1 % t2 = 1
t1 + 1 = 7
t1 - 1 = 5
</pre>
 
9,488

edits