For example strconv.Atoi.
Code:
package main
import (
"fmt"
"strconv"
)
func main() {
s := "123"
// string to int
i, err := strconv.Atoi(s)
if err != nil {
// ... handle error
panic(err)
}
fmt.Println(s, i)
}
Answer from peterSO on Stack OverflowFor example strconv.Atoi.
Code:
package main
import (
"fmt"
"strconv"
)
func main() {
s := "123"
// string to int
i, err := strconv.Atoi(s)
if err != nil {
// ... handle error
panic(err)
}
fmt.Println(s, i)
}
Converting Simple strings
The easiest way is to use the strconv.Atoi() function.
Note that there are many other ways. For example fmt.Sscan() and strconv.ParseInt() which give greater flexibility as you can specify the base and bitsize for example. Also as noted in the documentation of strconv.Atoi():
Atoi is equivalent to ParseInt(s, 10, 0), converted to type int.
Here's an example using the mentioned functions (try it on the Go Playground):
flag.Parse()
s := flag.Arg(0)
if i, err := strconv.Atoi(s); err == nil {
fmt.Printf("i=%d, type: %T\n", i, i)
}
if i, err := strconv.ParseInt(s, 10, 64); err == nil {
fmt.Printf("i=%d, type: %T\n", i, i)
}
var i int
if _, err := fmt.Sscan(s, &i); err == nil {
fmt.Printf("i=%d, type: %T\n", i, i)
}
Output (if called with argument "123"):
i=123, type: int
i=123, type: int64
i=123, type: int
Parsing Custom strings
There is also a handy fmt.Sscanf() which gives even greater flexibility as with the format string you can specify the number format (like width, base etc.) along with additional extra characters in the input string.
This is great for parsing custom strings holding a number. For example if your input is provided in a form of "id:00123" where you have a prefix "id:" and the number is fixed 5 digits, padded with zeros if shorter, this is very easily parsable like this:
s := "id:00123"
var i int
if _, err := fmt.Sscanf(s, "id:%5d", &i); err == nil {
fmt.Println(i) // Outputs 123
}
Which is the best way to convert int to string in golang ?
-
is plain wrong
-
is the most lightweight (in terms of dependency and performance)
-
is the most flexible
How to convert an int value to string in Go? - Stack Overflow
go - Golang: How to convert string to []int? - Stack Overflow
Which is the best way to convert int to string in golang ? : golang
Videos
There are some solutions:
-
stringValue = string(intValue)
-
stringValue = strconv.Itoa(intValue)
-
stringValue = fmt.Sprintf("%d", intValue)
I checked a project by a Guru at Google Engineers (link below), they use the third one. Could someone explain why ?
https://github.com/google/exposure-notifications-server/blob/main/internal/database/connection.go
-
is plain wrong
-
is the most lightweight (in terms of dependency and performance)
-
is the most flexible
The second one. Most times if you're in a pinch and write things quickly the third option might be done instead since fmt.Sprintf accepts a wide variety of types to be formatted into a string.
The second one is more performant and requires less heap memory allocations in comparison to fmt.Sprintf since it is specialized for formatting integers into strings.
The 1st one directly converts a number to it's string representation which is most often not what you want.
Use the strconv package's Itoa function.
For example:
package main
import (
"strconv"
"fmt"
)
func main() {
t := strconv.Itoa(123)
fmt.Println(t)
}
fmt.Sprintf("%v",value);
If you know the specific type of value use the corresponding formatter for example %d for int
More info - fmt
Would you please let me know if my way is correct?
If you just want to convert string(space separated integers) to []int
func AizuArray(A string, N string) []int {
a := strings.Split(A, " ")
n, _ := strconv.Atoi(N) // int 32bit
b := make([]int, n)
for i, v := range a {
b[i], err = strconv.Atoi(v)
if err != nil {
//proper err handling
//either b[i] = -1 (in case positive integers)
}
}
return b
}
then your approach is correct.
I tackle with this question.
In context of this question you want to take input from STDIN so should do,
package main
import (
"fmt"
)
func insertionSort(arr []int) {
//do further processing here.
fmt.Println(arr)
}
func main() {
var N int
fmt.Scanf("%d", &N)
b := make([]int, N)
for iter:=0;iter<N;iter++ {
fmt.Scanf("%d",&b[iter])
}
insertionSort(b)
}
I think you overcomplicating things unless I am missing something.
https://play.golang.org/p/HLvV8R1Ux-
package main
import (
"fmt"
"strings"
"strconv"
)
func main() {
A := "5 2 4 6 1 3"
strs := strings.Split(A, " ")
ary := make([]int, len(strs))
for i := range ary {
ary[i], _ = strconv.Atoi(strs[i])
}
fmt.Println(ary)
}