Search code examples
gostructdecimaloctal

Why does Go Programming treat any number starting with zero as an octal and how can I prevent this?


package main

type contactInfo struct {
    number int
    email  string
}

type person struct {
    firstName string
    lastName  string
    contact   contactInfo
}

func main() {
    user1 := person{
        firstName: "Anthony",
        lastName:  "Martial",
        contact: contactInfo{
            number: 07065526369,
            email: "tony@gmail.com",
        },
    }
    fmt.Println(user1)
}

When I assigned a value to the variable "number: 07065526369" an error comes up saying "invalid digit '9' in octal literal" and I'm trying to figure out a way to prevent it by making that number in base 10 rather than base 8 because I think Go automatically treats any number starting with zero as an octal


Solution

  • Even though Go 1.13 introduced a change in the integer literals, your int would still be interpreted as octal (which cannot have '9' in it, hence the error message)

    Octal integer literals: The prefix 0o or 0O indicates an octal integer literal such as 0o660.
    The existing octal notation indicated by a leading 0 followed by octal digits remains valid.

    Any Go library dealing with phone number would store it as string.
    And that data can be more detailed that one string.

    For instance dongri/phonenumber would follow the ISO 3166 COUNTRY CODES standard, with a struct like:

    type ISO3166 struct {
        Alpha2             string
        Alpha3             string
        CountryCode        string
        CountryName        string
        MobileBeginWith    []string
        PhoneNumberLengths []int
    }
    

    That is safer than an int, and offer a better validation.