go字符串转byte_三分钟学 Go 语言——常量+各种类型转换 - Go语言中文社区

go字符串转byte_三分钟学 Go 语言——常量+各种类型转换


代码位置

3f3ffd3e936b922d2122243396eaffca.png

常量

常量就是不可变的变量,定义方式

const identifier [type] = value

约定常量全大写表示

const A int = 1
const B = 1
const C, D, E = 1, 1, 1

一般常量被用于枚举

 const (
  Success = 0
  UnKonw  = 1
  Error   = 2
 )

不过要枚举还是用 go 自带的特殊常量好一点,这种特殊被认为是可以被编译器修改的常量

//const 出现时被重置为0,每出现一次自动加1
 const (
  F = iota
  G = iota
  H = iota
 )

F、G、H 值为0,1,2

当然可以简写成这样,效果是一样的。

 const (
  I = iota
  J
  K
 )

类型转换

没有什么好说的,和其他语言相似,类型转换都是类型+变量的形式,如下。

 var aInt int = 17

 // 一般用这种方式强制转
 fmt.Printf("转float64 %f  n", float64(aInt))
 fmt.Printf("转string %v  n", strconv.Itoa(aInt))
 fmt.Printf("转float64 %f  n", float64(aInt))[]

输出

转float64 17.000000  
转string 17  
转float64 17.000000

各种类型转字符串

 resString := fmt.Sprintf("%d %v %v", 1, "coding3min", true)
 fmt.Println(resString)

输出

1 coding3min true

stringbytes 的互相转换

// string  to bytes
 resBytes := []byte("asdfasdf")
 // bytes to string
 resString = string(resBytes)
 fmt.Println(resString)

输出

asdfasdf

这一节学完,你觉得最有用的部分是什么呢?

版权声明:本文来源CSDN,感谢博主原创文章,遵循 CC 4.0 by-sa 版权协议,转载请附上原文出处链接和本声明。
原文链接:https://blog.csdn.net/weixin_39844481/article/details/112511874
站方申明:本站部分内容来自社区用户分享,若涉及侵权,请联系站方删除。
  • 发表于 2021-06-13 18:35:35
  • 阅读 ( 723 )
  • 分类:Go

0 条评论

请先 登录 后评论

官方社群

GO教程

猜你喜欢