Go type conversions All In One
Go 语言
类型转换
https://go.dev/ref/spec#Conversions
The Go Programming Language Specification
Version of June 29, 2022
strconv
int to string
/**
*
* @author xgqfrms
* @license MIT
* @copyright xgqfrms
* @created 2023-01-07
*
* @description close-channel.go
* @augments
* @example
* @link
*
*/
package main
// import "fmt"
import (
"fmt"
// 字符串类型转换
"strconv"
)
func fibonacci(n int, c chan int) {
x, y := 0, 1
for i := 0; i < n; i++ {
c <- x
// switch
x, y = y, x + y
}
// 关闭通道
close(c)
}
func main() {
c := make(chan int, 10)
go fibonacci(cap(c), c)
// range 函数遍历每个从通道接收到的数据
// 因为 c 在发送完 10 个数据之后就关闭了通道,所以这里我们 range 函数在接收到 10 个数据之后就结束了。
// 如果上面的 c 通道不关闭,那么 range 函数就不会结束,从而在接收第 11 个数据的时候就阻塞了。
for i := range c {
// fmt.Println("fibonacci =", i)
// int to string ✅
str := strconv.Itoa(i)
fmt.Println("fibonacci " + str + " =", i)
// fmt.Println("fibonacci " + string(i) + " =", i)
// ❌ invalid operation: "fibonacci " + i (mismatched types untyped string and int)
// fmt.Println("fibonacci " + i + " =", i)
}
// ❌ range over c (variable of type chan int) permits only one iteration variable
// for i, v := range c {
// fmt.Println("i, v =", i, v)
// }
}
/*
$ go run close-channel.go
fibonacci 0 = 0
fibonacci 1 = 1
fibonacci 1 = 1
fibonacci 2 = 2
fibonacci 3 = 3
fibonacci 5 = 5
fibonacci 8 = 8
fibonacci 13 = 13
fibonacci 21 = 21
fibonacci 34 = 34
*/
/*
$ go run close-channel.go
fibonacci = 0
fibonacci = 1
fibonacci = 1
fibonacci = 2
fibonacci = 3
fibonacci = 5
fibonacci = 8
fibonacci = 13
fibonacci = 21
fibonacci = 34
*/
/*
$ go run close-channel.go
fibonacci = 0
fibonacci = 1
fibonacci = 1
fibonacci = 2
fibonacci = 3
fibonacci = 5
fibonacci = 8
= 13 cci
fibonacci = 21
fibonacci " = 34 "
*/
string to int
Go Docs
Documentation - The Go Programming Language
tutorial
https://go.dev/doc/tutorial/getting-started
tour
zh-Hans
https://tour.go-zh.org/welcome/1
https://tour.go-zh.org/basics/1
playground
https://go.dev/blog/playground
Go by Example