How to convert type to string type in Golang

PHPz
Release: 2023-04-25 10:22:40
Original
1200 people have browsed it

Golang is an efficient and strongly typed programming language. It provides many basic types and data structures, and also supports custom types. In program development, it is often necessary to convert types to string types, for example in logging or error messages. This article will introduce how to convert type to string type in Golang.

1. Use the strconv package

Golang provides the strconv package, which contains many functions for handling type conversion. Here are some examples:

1.1 Convert integer type to string type:

num := 42
str := strconv.Itoa(num) // "42"

1.2 Convert floating point type to string type:

fnum := 3.1415926
str := strconv.FormatFloat(fnum, 'f', 2, 64) // "3.14"

1.3 Convert Boolean type to string type:

bval := true
str := strconv.FormatBool(bval) // "true"

2 .Using the fmt package

The fmt package also provides some functions for type conversion. Here are some examples:

2.1 Convert integer type to string type:

num := 42
str := fmt.Sprintf("%d", num) // "42"

2.2 Convert floating point type to string type:

fnum := 3.1415926
str := fmt.Sprintf("%.2f", fnum) // "3.14"

2.3 Convert Boolean type to string type:

bval := true
str := fmt.Sprintf("%t", bval) // "true "

3. Custom type

If you need to convert the custom type to a string type, you can define a String() method in the structure of the custom type, which returns a A value of type string. For example:

type Person struct {

Name string
Age int
Copy after login

}

func (p Person) String() string {

return fmt.Sprintf("Name: %s, Age: %d", p.Name, p.Age)
Copy after login

}

Use this method to convert the Person type to a string type:

person := Person{

Name: "John",
Age: 30,
Copy after login

}
str := person.String() // "Name: John, Age: 30"

Summary:

This article introduces the method of converting type to string type in Golang and provides some examples. Basic types can be easily converted to string types using the strconv and fmt packages. If you need to convert a custom type to a string type, you can define the String() method in the structure. In actual programming, choose the appropriate method for type conversion as needed.

The above is the detailed content of How to convert type to string type in Golang. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!