9

I'm working on a piece of code that returns uint data type. I need to convert uint datatype into string for further processing.

I've already tried strconv package and none of the functions accept uint. Golang Documentation: https://golang.org/ref/spec#Numeric_types states that uint are platform dependent. Is that the reason we don't have any standard functions for conversion?

type Example{
    Id uint    //value 3
    name string
}

Need to extract Id into a string.

Expected: "3" Actual: N/A

0

2 Answers 2

34

Use strconv.FormatUint():

package main

import (
    "fmt"
    "strconv"
)

func main() {
    var n uint = 123
    var s string = strconv.FormatUint(uint64(n), 10)
    fmt.Printf("s=%s\n", s)
}

(Go Playground)

Sign up to request clarification or add additional context in comments.

7 Comments

Umm.. That's not correct. I tried it. It gives "Cannot use Example.Id type uint as type uint64
@KaushalShah my fault, you need to convert it to uint64 explicitly.
All builtin types must be available regardless of the architecture.
The uint64 type is available on all architectures and is guaranteed to have a size greater than or equal to the uint type. The code works the same on all architectures.
No. Math is math. If it gave a different answer, it would be fundamentally broken.
|
0

In Go (Golang), converting a uint to a string is a straightforward task that can typically be achieved using the fmt.Sprintf function from the standard library's fmt package. This function is very versatile for formatting data types into strings.

Here’s how you can convert a uint variable to a string using fmt.Sprintf:

Example Code:

package main

import (
    "fmt"
)

func main() {
    var myUint uint = 10
    myString := fmt.Sprintf("%d", myUint)
    fmt.Println("The string representation of myUint is:", myString)
}

1 Comment

While being technically correct, I would advise against fmt.Sprintf for single (u)ints, because it's slower and produces more GC garbage. If you need to make a somewhat complex string then sure, otherwise its better to use strconv methods. Uber's styleguide also suggests that: github.com/uber-go/guide/blob/master/…

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.