golang type conversion
2024-09-05 07:23:38
map[string]interface{}
is not the same as map[string]string
. Type interface{}
is not the same as type string
.
If they are both map[string]string
:
package main
import "fmt"
func main() {
v := map[string]string{"hello": "world"}
checkCast(v)
}
func checkCast(v interface{}) {
_, isCorrectType := v.(map[string]string)
if !isCorrectType {
fmt.Printf("incorrect type")
return
}
}
Output:
[no output]
The statement v.(map[string]string)
is a type assertion, not a cast.
The Go Programming Language Specification
For an expression
x
of interface type and a typeT
, the primary expressionx.(T)
asserts that
x
is notnil
and that the value stored inx
is of typeT
. The notationx.(T)
is called a type assertion.
Go has conversions.
The Go Programming Language Specification
Conversions are expressions of the form
T(x)
whereT
is a type andx
is an expression that can be converted to typeT
.
- is there a way to cast in Go? – Karan Jul 4 '14 at 19:56
- 1@Karan: See my revised answer. Go has conversions. – peterSO Jul 4 '14 at 20:05
最新文章
- bzoj 2648 KD-tree
- 去除select的样式
- UIKit框架之UITouch
- 初识canvas,使用canvas做一个百分比加载进度的动画
- Strobogrammatic Number
- java去处重复输出
- js方法收藏
- hdu 3549 Flow Problem 网络流
- python(7)–类的多态实现
- 学习笔记之Linux Shell脚本教程:30分钟玩转Shell脚本编程
- 验证角谷猜想(hd1279)
- 用邻接表实现DFS和BFS
- uva 1025
- 关于Java通过JNI调用C 动态链接库(DLL)
- 移动H5开发入门知识,CSS的单位汇总与用法
- Red Hat 9.0 Linux 分辨率修改
- SQLServer修改表数据
- LeetCode(58): 最后一个单词的长度
- 添加 vip
- Xib给特定view添加手势