SoFunction
Updated on 2025-03-05

Summary of the method of converting basic data types and strings

Go basic data types and strings are converted

Go language Chinese document:

Go language standard library document Chinese version | Go language Chinese website | Golang Chinese community | Golang Chinese version of Go language document Chinese version, Go language Chinese website, China Golang Community, Go Language Learning Garden, is committed to building a complete Golang Chinese community, a learning home for Go language enthusiasts.

/pkgdoc

1. Convert basic types to strings (string)

method

("%parameter", expression)

Notice:

  • The parameter needs to match the data type of the expression
  • () Return string result after conversion
func main() {
    var num1 int = 99
    var num2 float64 = 23.55
    var b bool = true
    var mych byte = 'd'
    var st = string  // Empty string    // Convert to string    str = ("%d", num1)
    str = ("%f", num2)
    str = ("%t", b)
    str = ("%c", mych)
}

strconv package

package main
import (
    "fmt"
    "strconv"
)
func main() {
    var num1 int = 99
    var num2 float64 = 23.55
    var b bool = true
    var mych byte = 'd'
    var st = string  // Empty string    str = (int64(num1), 10)  // Transfer out the decimal string    ("type: %T, str: %q\n", str, str)  // Format output    // "f" is a representation format after converting it to floating point data. See the document for details    // 10 Accuracy    // 64 convert to float64    str = (num2, "f", 10, 64)  // 
    str = (b)  // Export boolean type string    // Convert integer variables into strings, special case functions    var num3 int = 333
    str = (num3)   // Here num3 is int type, if it is not necessary to display the conversion first}

2. Convert strings to basic data type strconv package

func main() {
    // Boolean type conversion    var str string = "true"
    var b bool 
    b, _ = (str)
    // Integer conversion    var str2 string = "232"
    var n int64
    var n2 int
    // 10 convert to decimal    // 0, 8, 16, 32, 64 represents int, int8, int16, int32, and int64 respectively    n, _ = (str2, 10, 64)
    n2 = int(n)  // Get the value of type int and display the conversion    // Floating point conversion    var str3 string = "22.33"
    var f float64
    f, _ = (str3, 64)
}

Notice:

When converting a string type to a primitive type, you must ensure that the string type is valid; if it is an invalid value, the conversion will be successful, but the converted value is the default value of the primitive type. For example, "ddd" cannot be converted into an integer. If you do this, golang will directly convert it to 0

Replenish:

Go - Convert between a basic data type and its string representation

1. Convert between a basic data type and its string representation

The values ​​of basic types have a string representation, such as numeric type values.1The string is represented as"1", the characters are encoded asUnicodeorUTF-8, the encoding of the number isint, the data formats stored at the underlying level are essentially different, and the conversion of basic types is essentially just a grammatical semantic transformation.

1.1 Basic Go language types

  • Integer: signedint int8 int16 int32 int64Unsigned:uint uint8 uint16 uint32 uint64
  • Decimals:float32 flat63
  • String:string

1.2 There may be errors during the conversion process

There will be no errors in the conversion of the basic data type to the string representation, but the conversion of the character representation to the basic type may have the following errors

  • Out of the target type representation range
package main
import (
	"fmt"
	"strconv"
)
func main() {
	numStr := "400"
	// 400 The numeric value has exceeded the range represented by type int8(-128, 127)	num, err := (numStr, 10, 8)
	if err != nil {
		(err)
		return
	}
	("conv result:", num)
}
// Output:: parsing "400": value out of range
  • Not in line with the target type syntax
package main
import (
	"fmt"
	"strconv"
)
func main() {
	numStr := "xx"
	// The xx string value cannot be expressed as the corresponding integer value	num, err := (numStr, 10, 8)
	if err != nil {
		(err)
		return
	}
	("conv result:", num)
}
// Output:: parsing "400": value out of range

2. Convert

  • Conversion between string and quotes
package main
import (
	"fmt"
	"strconv"
)
func main() {
	name := "dream_fish n"
	// Add quotes	("result:", (name))
	// Remove quotes	school := `"University"`
	school_, err := (school)
	if err != nil {
		("err:", err)
		return
	}
	("result:", school_)
}
  • Conversion between string and boolean type

String conversionbooltype

package main
import (
	"fmt"
	"strconv"
)
func main() {
	// Contains all values ​​that can be converted to bool type	boolStringValues := []string{"1", "0", "t", "f", "true", "false", "True", "False"}
	// Convert	for _, b := range boolStringValues {
		result, err := (b)
		if err != nil {
			("parse value: %s err:%s\n", b, err)
			continue
		}
		("parse value: %s err:%s\n", b, result)
	}
}

boolType to string

package main
import (
	"fmt"
	"strconv"
)
func main() {
	// Contains a value of boolean type	boolValues := []bool{false, true}
	// Convert	for _, b := range boolValues {
		result := ((b))
		("format value: %t err:%s\n", b, result)
	}
}
  • Conversion between a numeric value and a string

String to value

package main
import (
	"fmt"
	"strconv"
)
func main() {
	// Convert to int8 type	int8String := "122"
	// The first parameter is the string that needs to be converted, the second parameter is the int type binary, and the third parameter is the number of bits	intNum, err := (int8String, 10, 8)
	if err != nil {
		("err:", err)
	}
	("int8 num:", intNum)
	// String positive integer	uintNum, err := (int8String, 10, 8)
	if err != nil {
		("err:", err)
	}
	("uint8 num:", uintNum)
	// String to floating point number	floatNumStr := "67.9"
	floatNum, err := (floatNumStr, 64)
	if err != nil {
		("err:", err)
	}
	("float64 num:", floatNum)
}

Value to string

  • strconvPackedFormatSeries Methods
package main
import (
	"fmt"
	"strconv"
)
func main() {
	//Correction and convert strings	intNum := int64(8)
	("%s\n", (intNum, 10))
	// Floating point number to string	result := (88.9, 'f', 2, 64)
	("float to str:", result)
	// Bool type to string	("bool to str:", (true))
	// Unsigned cleansing	("uint to str", (111, 10))
}
  • fmtBagSprintSeries Methods
package main
import (
	"fmt"
)
func main() {
	//Correction and convert strings	intValue := int64(8)
	boolValue := true
	floatValue := 44.2
	uintValue := 33
	result := ("int: %d, bool: %t, float: %f, unit: %d", intValue, boolValue, floatValue, uintValue)
	(result)
}
  • strconvPackedAtoiandItoaThe method is actuallyParseInt(s, 10, 0) FormatInt(i, 10)Abbreviation of
package main
import (
	"fmt"
	"strconv"
)
func main() {
	// Convert int type value to string	result := (100)
	(result)
	// Convert the string value to a value of type int	intString := "200"
	intValue, err := (intString)
	if err != nil {
		panic(err)
	}
	(intValue)
}

3. Append system method

Add to convert to basic type and string representation

package main
import (
	"fmt"
	"strconv"
)
func main() {
	// Basic data type	intValue := int64(100)
	boolValue := true
	floatValue := 5.4
	buf := []byte("result:")
	resultValue := (buf, floatValue, 'f', 2, 64)
	(string(resultValue))
	resultValue = (buf, intValue, 10)
	(string(resultValue))
	resultValue = (buf, boolValue)
	(string(resultValue))
}

4. Summary

  • ParseSeries methods, attempting to convert string representation to base type,FormationThe series methods convert the primitive type to a string representation,AppendThe method is a shortcut to add a primitive type string representation to a byte slice

This is the article about the summary of Go basic data types and string conversion methods. For more relevant basic data types, please search for my previous articles or continue browsing the related articles below. I hope you will support me in the future!