Using decimal package in Go to store currency

Issue

I want to use a price friendly data type in Go. I have found the decimal package to do so.

package main

import (
        "github.com/shopspring/decimal"
)

type MyStruct struct {
        price           Decimal
        quantity        int
}

func main() {

        var a MyStruct

        a.price, _ = decimal.NewFromString("45.34")
        a.quantity = 3

}

However, when I try to define a Decimal value according to the documentation I get undefined: Decimal:

% go build .
# _/home/user/test0
./test.go:8:9: undefined: Decimal

Any ideas on how to further troubleshoot this would be welcomed.

Solution

Literals exported from a package must be referred to using the fully qualified name.

In your code, the Decimal type is from the decimal package. Hence it must be used as decimal.Decimal just as you have done in decimal.NewFromString.

Answered By – Chandra Sekar

Answer Checked By – Jay B. (GoLangFix Admin)

Leave a Reply

Your email address will not be published.