Skip to content

Instantly share code, notes, and snippets.

@nikolaydubina
Last active November 19, 2022 15:08
Show Gist options
  • Save nikolaydubina/681f7668e955fbde14c6e4a801c560aa to your computer and use it in GitHub Desktop.
Save nikolaydubina/681f7668e955fbde14c6e4a801c560aa to your computer and use it in GitHub Desktop.
package main
import (
"errors"
"fmt"
"unsafe"
)
type Currency uint8
const (
UnknownCurrency Currency = iota
SGD
PHP
PKR
JOD
JPY
VND
KRW
)
// Decimals multilier
func (c Currency) Decimals() uint16 {
switch c {
case JPY, VND, KRW:
return 1
case SGD:
return 100
case JOD:
return 1000
default:
return 100
}
}
type Money struct {
Amount int64 `json:"amount"`
Currency Currency `json:"currency"`
}
var ErrNil = errors.New("money is nil")
func (a Money) Validate() error {
if a.Currency == UnknownCurrency {
return ErrNil
}
return nil
}
func (a Money) Add(b Money) Money {
if a.Currency != b.Currency {
return Money{}
}
if (a == Money{}) || (b == Money{}) {
return Money{}
}
return Money{
Amount: a.Amount + b.Amount,
Currency: a.Currency,
}
}
func main() {
asgd := Money{Amount: 10, Currency: SGD}
akrw := Money{Amount: 10000, Currency: KRW}
fmt.Println(asgd.Add(akrw).Add(akrw))
fmt.Println(asgd.Add(akrw).Add(akrw).Validate())
fmt.Println(asgd.Add(akrw))
fmt.Println(asgd.Add(akrw).Validate())
fmt.Println(Money{10, SGD}.Add(Money{11, SGD}))
var x int64 = 10
fmt.Printf("size of int64 %d\n", unsafe.Sizeof(x))
y := struct {
A int64
}{10}
fmt.Printf("size of struct with int64 %d\n", unsafe.Sizeof(y))
z := struct {
A int64
B bool
}{10, true}
fmt.Printf("size of struct with int64 and bool %d\n", unsafe.Sizeof(z))
fmt.Printf("size in sgd %d\n", unsafe.Sizeof(asgd))
fmt.Printf("size in krw %d\n", unsafe.Sizeof(akrw))
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment