How to convert a string to a number (int) in Go?
Hi everyone! I just started learning Go and encountered a problem converting a string to an integer. I need to read a number from a command-line argument or from a text file, but in Go strings and numbers are different types, and you can't simply assign a string to an int variable.\n\nFor example, I have this code:\n\n```go\npackage main\n\nimport "fmt"\n\nfunc main() {\n var s string = "42"\n var i int = s // Error!\n fmt.Println(i)\n}\n```\n\nThe compiler gives an error: `cannot use s (type string) as type int in assignment`. I understand that explicit conversion is needed, but how to do it correctly? In Python I wrote `int("42")`, but in Go `int(s)` doesn't work.\n\nI tried using the `strconv` package, but I didn't quite understand how to use it. Please tell me how to do this in Go.
No answers yet.
Log in to leave an answer
Blogs