Home  >  Article  >  Backend Development  >  Golang data conversion method: master the core technology of data conversion and easily cope with various scenarios

Golang data conversion method: master the core technology of data conversion and easily cope with various scenarios

PHPz
PHPzOriginal
2024-02-22 18:06:041129browse

Golang data conversion method: master the core technology of data conversion and easily cope with various scenarios

Golang data conversion method: Master the core technology of data conversion, easily cope with various scenarios, need specific code examples

In Golang development, data conversion is a very important Common operations. Whether it is converting data format to another format or converting data type to another type, some technical means are required to achieve it. The quality and efficiency of data conversion directly affect the performance and stability of the program. Therefore, it is very important to master the core technology of data conversion.

This article will introduce some commonly used Golang data conversion methods, and use specific code examples to help readers better understand and master these technologies.

1. Conversion between strings and integers

In Golang, conversion between strings and integers is a relatively common operation. The following is a sample code to convert a string to an integer:

package main

import (
    "fmt"
    "strconv"
)

func main() {
    str := "123"
    num, err := strconv.Atoi(str)
    if err != nil {
        fmt.Println("转换失败:", err)
        return
    }
    fmt.Println(num)
}

In the above code, the string can be converted to an integer through the strconv.Atoi function. If the conversion fails, it will Return an error.

Similarly, if you want to convert an integer to a string, you can use the strconv.Itoa function:

package main

import (
    "fmt"
    "strconv"
)

func main() {
    num := 123
    str := strconv.Itoa(num)
    fmt.Println(str)
}

2. Conversion between structure and JSON

In Golang, conversion between structures and JSON is also a relatively common operation. The following is a sample code that converts a structure into a JSON string:

package main

import (
    "encoding/json"
    "fmt"
)

type Person struct {
    Name string `json:"name"`
    Age  int    `json:"age"`
}

func main() {
    person := Person{Name: "Alice", Age: 25}
    jsonStr, err := json.Marshal(person)
    if err != nil {
        fmt.Println("转换失败:", err)
        return
    }
    fmt.Println(string(jsonStr))
}

In the above code, the structure can be converted into a JSON string through the json.Marshal function.

If you want to convert a JSON string into a structure, you can use the json.Unmarshal function:

package main

import (
    "encoding/json"
    "fmt"
)

type Person struct {
    Name string `json:"name"`
    Age  int    `json:"age"`
}

func main() {
    jsonStr := `{"name":"Bob","age":30}`
    var person Person
    err := json.Unmarshal([]byte(jsonStr), &person)
    if err != nil {
        fmt.Println("转换失败:", err)
        return
    }
    fmt.Println(person)
}

3. Interface type assertion

In Golang Interface is a very flexible data type that is often used to implement polymorphism of data. But when using interfaces, sometimes it is necessary to convert the interface into a specific type. At this time, you can use interface type assertion to achieve:

package main

import "fmt"

type Shape interface {
    Area() float64
}

type Circle struct {
    Radius float64
}

func (c Circle) Area() float64 {
    return 3.14 * c.Radius * c.Radius
}

func main() {
    var s Shape
    s = Circle{Radius: 5}
    circle, ok := s.(Circle)
    if !ok {
        fmt.Println("类型断言失败")
        return
    }
    fmt.Println(circle.Area())
}

In the above code, the interface s is converted into a specific type through s.(Circle) Circle, and determine whether the conversion is successful.

Through the above introduction, readers can better understand and master the core technology of data conversion in Golang. After mastering these technologies, readers can easily handle various data conversion scenarios and improve program performance and stability. I hope the content of this article will be helpful to readers.

The above is the detailed content of Golang data conversion method: master the core technology of data conversion and easily cope with various scenarios. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn