
编程开发
切片copy
当我们需要在Go语言中复制一个切片时,我们可以使用内置的copy函数。copy函数可以将一个切片的元素复制到另一个切片中。下面是一个示例: 在上面的示例中,我们首先创建了一个源切片
package main
// 吴老二 个人博客地址 http://www.wulaoer.org
import (
"fmt"
"strconv"
)
func main() {
wulaoer := "987654321"
if wulaoer, err := strconv.Atoi(wulaoer); err == nil {
fmt.Printf("字符串转整数结果:i=%d, type: %T\n",wulaoer,wulaoer)
}
}
输出结果:
字符串转整数结果:i=987654321, type: int这里使用了strconv.Atoi()函数,在Atoi()中的代码是这样的func Atoi(s string) (int, error),返回的是两个值,一个是转换成int的值,一个是返回值的判断是否转换成功。我们可以不用判断,直接返回结果。
package main
// 吴老二 个人博客地址 http://www.wulaoer.org
import (
"fmt"
"strconv"
)
func main() {
wulaoer := "987654321"
wulaoer := "987654321"
i, _ := strconv.Atoi(wulaoer)
wolf := reflect.TypeOf(wulaoer)
wolf2 := reflect.TypeOf(i)
fmt.Println("转换后原字符串,原字符串类型,转换后整数,转换后整数类型",wulaoer,wolf,i,wolf2)
}
输出结果:
转换后原字符串,原字符串类型,转换后整数,转换后整数类型 987654321 string 987654321 int这里不进行判断,直接进行转换,相比简单一些,不过使用的都是同一个方法。
package main
// 吴老二 个人博客地址 http://www.wulaoer.org
import (
"fmt"
"strconv"
)
func main() {
wulaoer := "987654321"
if wulaoer,err := strconv.ParseInt(wulaoer, 10 ,64); err == nil {
fmt.Printf("字符串转int64结果i=%d,type:%T\n",wulaoer,wulaoer)
}
}
输出结果:
字符串转int64结果i=987654321,type:int64这里使用的是字符串转整数,使用了10进制去解析,保存类型为64.还可以使用浮点数或者布尔类型以及无符合整型等等,看看他们的方法有哪些?浮点数可以使用ParseFloat(),布尔类型可以使用ParseBool(),无符号整型可以使用ParseUint()。看下面的例子:
package main
// 吴老二 个人博客地址 http://www.wulaoer.org
import (
"fmt"
"reflect"
"strconv"
)
func main() {
wulaoer := "987654321"
b, _ := strconv.ParseBool("true")
b_type := reflect.TypeOf(b)
fmt.Println("布尔类型值,转换后类型",b,b_type)
f, _ := strconv.ParseFloat("3.1415926",64)
f_type := reflect.TypeOf(f)
fmt.Println("浮点数类型值,转换后类型",f,f_type)
wulaoer, _ := strconv.ParseUint("27",10,64)
wulaoer_type := reflect.TypeOf(wulaoer)
fmt.Println("无符号整数类型值,转换后类型",wulaoer,wulaoer_type)
wolf, _ := strconv.ParseInt("-27",10,64)
wolf_type := reflect.TypeOf(wolf)
fmt.Println("整数类型值,转换后类型",wolf,wolf_type)
}
输出结果:
布尔类型值,转换后类型 true bool 浮点数类型值,转换后类型 3.1415926 float64 无符号整数类型值,转换后类型 27 uint64 整数类型值,转换后类型 -27 int64这就是布尔类型,字符串对浮点数,整型的转换过程。以上是string类型转换为给定的类型,下面进行给定类型转换为string类型。
评论 0