golang作为强类型语言,我们在日常开发过程中,遇到类型转换的场景也非常多,本文整理我在工作开发中遇到过的类型转换实践。
# String To Other
str := "10"
int, err := strconv.Atoi(str)
str := "10"
int, err := strconv.ParseInt(str, 10, 0)
str := "10"
int, err := strconv.ParseInt(str, 10, 8)
int32也叫做rune
str := "10"
int, err := strconv.ParseInt(str, 10, 64)
ret, _ := strconv.ParseFloat("3.14159", 32)
fmt.Println(ret)
ret, _ := strconv.ParseFloat("3.14159", 64)
fmt.Println(ret)
s1 := "hello"
b := []byte(s1)
func JsonToMap(jsonStr string) (m map[string]string, err error) {
err = json.Unmarshal([]byte(jsonStr), &m)
if err != nil {
return nil, err
}
return
}
# Other To String
var s1 []byte
fmt.Println(string(s1))
int, int32, int16, int8 转十进制字符串
# Map To Other
func MapToJson(m map[string]string) (string, error) {
result, err := json.Marshal(m)
if err != nil {
return "", nil
}
return string(result), nil
}
func MapToSlice(m map[int]string) []string {
s := make([]string, 0, len(m))
for _, v := range m {
s = append(s, v)
}
return s
}
# Json To Other
func JsonToMap() {
jsonStr := `{"name": "eryajf","age": 18}`
var mapResult map[string]interface{}
err := json.Unmarshal([]byte(jsonStr), &mapResult)
if err != nil {
fmt.Println("JsonToMap err: ", err)
}
fmt.Println(mapResult)
}
package main
import (
"encoding/json"
"fmt"
)
type People struct {
Name string `json:"name"`
Age int `json:"age"`
}
func main() {
jsonStr := `{"name": "eryajf","age": 18}`
var people People
json.Unmarshal([]byte(jsonStr), &people)
fmt.Println(people.Name, people.Age)
}
# Struct To Other
package main
import (
"encoding/json"
"fmt"
)
type People struct {
Name string `json:"name"`
Age int `json:"age"`
}
func main() {
p := People{
Name: "eryajf",
Age: 18,
}
jsonBytes, err := json.Marshal(p)
if err != nil {
fmt.Println(err)
}
fmt.Println(string(jsonBytes))
}
未完。。。