go 语言开发中,经常会在函数中碰到使用 insterface{} 作为接收任意参数,但是我们接收的数据经常是需要做类型转换,由于是初学者,因此,初次转换我是直接就

func New(parameters map[string]interface{}) (*driver, error){
hostname, _ := string(parameters["HostName"])
fmt.Println(parameters)
machines := []string{hostname}
client := etcd.NewClient(machines)
return &driver{
etcd: client,
}, nil
}

可以看到,我直接使用了 hostname, _ := string(parameters["HostName"]) 进行转换,不出意外,发生了一些不愉快的错误

[vagrant@localhost etcd]$ godep go test
# configcenter/storage/driver/etcd
./etcd.go::: cannot assign values to variables
./etcd.go::: cannot convert parameters["HostName"] (type interface {}) to type string: need type assertion
FAIL configcenter/storage/driver/etcd [build failed]
godep: go exit status

提示类型无法进行转换,于是陷入了深深的沉思中——看到了关键语句

 need type assertion

顺利的找到了解决方式:

# 替换强制转换语句
hostname := string(parameters["HostName"])
# 如下,为正确表达式
hostname := parameters["HostName"].(string)
hostname, ok := parameters["HostName"].(string)

但是,依然没有想出来是什么原因。于是上了Stack Overflow,有大神的地方果然不一样。几经调整检索参数,终于还是让我找到了原因,回答者原话如下:

The reason why you cannot convert an interface typed value are these rules in the referenced specs parts:

Conversions are expressions of the form T(x) where T is a type and x is an expression that can be converted to type T.

....

A non-constant value x can be converted to type T in any of these cases:

  1. x is assignable to T.
  2. x's type and T have identical underlying types.
  3. x's type and T are unnamed pointer types and their pointer base types have identical underlying types.
  4. x's type and T are both integer or floating point types.
  5. x's type and T are both complex types.
  6. x is an integer or a slice of bytes or runes and T is a string type.
  7. x is a string and T is a slice of bytes or runes.

船新智能翻译,给你不一样的体验:

  1. x被赋值为t。
  2. x的类型和t具有相同的基础类型。
  3. x的类型和t是未命名的指针类型,它们的指针基类型具有相同的基础类型。
  4. x的类型和t都是整数或浮点类型。
  5. x的类型和t都是复杂类型。
  6. x是一个整数或一片字节或符文,且T是一个字符串类型。
  7. X是一个字符串,t是一片字节或字符。

但是,

  hostname := string(parameters["HostName"])

不属于上述七个情景中的一个。



最新文章

  1. C++常见笔试面试要点以及常见问题
  2. Java中读文件操作
  3. Gradle's dependency cache may be corrupt解决方法
  4. RabbitMQ 入门 Helloworld
  5. C# WPF MVVM 实战 – 5- 用绑定,通过 VM 设置 View 的控件焦点
  6. Linux中的free命令
  7. GitHub上整理的一些工具,求补充
  8. Cantor表(中等)
  9. InstallShield 工程类型MSI 使用过程中碰到的问题及解决方法。
  10. Thinking in scala (1)----类
  11. 获取CPU和内存呢信息
  12. 主机ping通虚拟机,虚拟机ping通主机解决方法(NAT模式)
  13. Git文件状态描述
  14. [PHP] PHP服务器接口SAPI中的结构体
  15. DOM节点的创建
  16. adSage :2013年教育行业搜索引擎投放分析报告
  17. laravel5.5 Syntax error or access violation: 1071 Specified key was too long
  18. js 使用a标签 下载资源
  19. Oracle 22表空间
  20. 安装opencv2.4.9

热门文章

  1. xhEditor编辑器上传图片到 OSS
  2. 【Java基础】java中的反射机制与动态代理
  3. NFS基础优化
  4. CSS3-文本-word-wrap,word-break,white-space
  5. asyn_fifo
  6. 剑指Offer(书):合并两个排序的列表
  7. 误删除innodb ibdata数据文件-之恢复
  8. python基础学习笔记——初识函数
  9. 【边双连通】poj 3352 Road Construction
  10. Linux之VMware虚拟机取消DHCP