Understand the contract

An explicit conversion such as float64(n) changes a value to another compatible type. Parsing a textual number is a different operation: strconv.Atoi reads decimal text and returns an int plus an error. Use parsing for user input and conversions when the source value already has a numeric type.

Go requires explicit conversions between distinct numeric variable types. Converting a float to an integer discards its fractional part toward zero. Converting to a narrower integer can lose high bits without returning an error, so validate the range before storing a large input in a small type.

Work through the example

The example accepts the string "42", checks the returned error and computes half using floating-point division. Atoi also rejects input outside the int range for the platform. If a protocol requires exactly 64 bits, use strconv.ParseInt with base 10 and bitSize 64 instead.

package main

import (
    "fmt"
    "strconv"
)

func main() {
    n, err := strconv.Atoi("42")
    if err != nil {
        fmt.Println("invalid number:", err)
        return
    }
    fmt.Println(float64(n) / 2)
}

Watch this boundary

string(65) produces the UTF-8 representation of the Unicode code point 65, which is "A". It does not produce the decimal digits "65". Use strconv.Itoa for that output. Keep conversions, formatting and parsing separate when reading a data flow.

Practice with a changed input

Change the input to "forty-two", then to " 42 ". Decide whether your application should trim whitespace with strings.TrimSpace before parsing.

References & further reading

Need help with your Go backend?

I work with engineering teams on focused Go and Kubernetes platform engagements, with limited consulting availability.

Explore Go consulting services