Home >Backend Development >Golang >Golang data conversion method: convert between different data types elegantly
Golang is a powerful programming language. Its simplicity and efficiency make it one of the preferred languages for many developers. In actual development, we often encounter conversion problems between different data types, and how to perform data conversion gracefully has become an important skill. This article will discuss how to elegantly convert between different data types in Golang through specific code examples.
In Golang, converting string to integer is a common operation. This functionality can be achieved using the built-in strconv
package. The following is a sample code:
package main import ( "fmt" "strconv" ) func main() { str := "123" num, err := strconv.Atoi(str) if err != nil { fmt.Println("转换失败:", err) return } fmt.Println("转换后的整数:", num) }
As opposed to converting string to integer, converting integer to string is also a common task. You can use the Itoa
function in the strconv
package to implement the function of converting integers to strings. The following is a sample code:
package main import ( "fmt" "strconv" ) func main() { num := 123 str := strconv.Itoa(num) fmt.Println("转换后的字符串:", str) }
In Golang, arrays and slices are two commonly used data structures. Sometimes we need to convert an array to a slice or a slice to an array. The following is a sample code:
package main import "fmt" func main() { arr := [3]int{1, 2, 3} slice := arr[:] fmt.Println("数组转切片:", slice) slice2 := []int{4, 5, 6} arr2 := [3]int{} copy(arr2[:], slice2) fmt.Println("切片转数组:", arr2) }
In actual development, conversion between structure and JSON is a very common operation. Golang provides the encoding/json
package to convert structures and JSON data. The following is a sample code:
package main import ( "encoding/json" "fmt" ) type Person struct { Name string `json:"name"` Age int `json:"age"` } func main() { p := Person{Name: "Alice", Age: 30} jsonData, err := json.Marshal(p) if err != nil { fmt.Println("转换失败:", err) return } fmt.Println("结构体转JSON:", string(jsonData)) var p2 Person err = json.Unmarshal(jsonData, &p2) if err != nil { fmt.Println("转换失败:", err) return } fmt.Println("JSON转结构体:", p2) }
Through the above code example, we understand how to elegantly convert between different data types in Golang. These conversion operations are often used in actual development. Mastering these techniques can allow us to deal with data conversion issues more efficiently. I hope this article can be helpful to you, and you are welcome to share more tips and experiences in Golang data conversion.
The above is the detailed content of Golang data conversion method: convert between different data types elegantly. For more information, please follow other related articles on the PHP Chinese website!