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"])

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



(type interface {}) to type string的更多相关文章

  1. Golang报错:Cannot convert expression of type interface{} to type []byte

    在使用golang实现后端登录逻辑的时候,碰到下面的问题:Cannot convert expression of type interface{} to type []byte 首先介绍下问题出现的 ...

  2. Go语言中cannot convert adminname (type interface {}) to type *: need type assertion的解决办法

    解决的办法是把string(adminname)替换为adminname.(string).其它类型也是类似.

  3. 【区分】Typescript 中 interface 和 type

    在接触 ts 相关代码的过程中,总能看到 interface 和 type 的身影.只记得,曾经遇到 type 时不懂查阅过,记得他们很像,相同的功能用哪一个都可以实现.但最近总看到他们,就想深入的了 ...

  4. Exception in thread "main" org.apache.ibatis.binding.BindingException: Type interface com.test.bean.groupMapper is not known to the MapperRegistry.

    Exception in thread "main" org.apache.ibatis.binding.BindingException: Type interface com. ...

  5. 解决 'Could not convert variant of type (NULL) into type (String)

    写存储过程中有不允许为空的字段,在客户端转化取数时显示 Could not convert variant of type (NULL) into type (String) 可以在存储过程中使用is ...

  6. ssm之mapper异常 Result Maps collection already contains value for com.ssj.mapper.UserMapper 和 Type interface com.ssj.mapper.UserMapper is already known to the MapperRegistry.

    异常一:Result Maps collection already contains value for com.ssj.mapper.XXXMapper 原因分析:XXXmapper.xml文件中 ...

  7. 报错org.apache.ibatis.binding.BindingException: Type interface com.atguigu.mybatis.bean.dao.EmployeeMapper is not known to the MapperRegistry.

    报错org.apache.ibatis.binding.BindingException: Type interface com.atguigu.mybatis.bean.dao.EmployeeMa ...

  8. Eclipse 出现select type (? = any character,*= any String,Tz=TimeZone)

    在eclipse中想运行project的时候,往往是右键项目名称---->run As --->Java Application 但是会弹出窗口显示select type (? = any ...

  9. MyBatis—— org.apache.ibatis.binding.BindingException: Type interface com.web.mybatis.i.PersonMapper is not known to the MapperRegistry.

    报错信息: Exception in thread "main" org.apache.ibatis.binding.BindingException: Type interfac ...

随机推荐

  1. 初涉2-SAT

    2-SAT:有趣的图论模型 什么是2-SAT SAT是适定性(Satisfiability)问题的简称.之所以研究2-sat是因为当k>2时,k-sat问题已经被证明是NPC的了. 2-sat问 ...

  2. RuntimeError: Failed to init API, possibly an invalid tessdata path: E:\python36\报错

    OCR:光学识别符,tesserocr是python中一个OCR识别库,是对tesseract做的一个python的 API封装,所以它的核心是tesseract 在这里我安装的版本是:tessera ...

  3. 【Python学习之一】list与tuple

    list -> [] list是python内置的有序集合数据类型,可随时添加和删除元素.例如:创建一个动物的列表: animal = ['cat', 'dog', 'pig' len()函数可 ...

  4. Python Third Day-函数

    ''' 为什么要有函数?没有函数带来的困扰? 组织结构不清晰,可读性差 代码冗余 可扩展性差 什么是函数 具备某一个功能的工具--->函数 事先准备工具->函数的定义 拿来就用.重复使用- ...

  5. strcpy与strcat函数原型

    1.strcpy函数原型 char *my_strcpy(char *dest,const char *src)    //const使在函数中不能修改*src其原先的值{ char *strDest ...

  6. awk支持多个记录分隔符的写法

    awk的-F参数可以指定新的记录分隔符,有些时候可能需求指定多个分隔符,比如下面的内容 width:720 height:360 如果需要取出width和height后面的值的话,一般大家会这样做,即 ...

  7. cf891a Pride

    倘若存在 1,那么答案是 \(n-cnt_1\). 否则,设最短的公约数为 1 的区间长度为 \(minlen\),答案是 \(minlen-1+n-1\). #include <iostrea ...

  8. Configure Always On Availability Group for SQL Server on Ubuntu

    下面简单介绍一下如何在Ubuntu上一步一步创建一个SQL Server AG(Always On Availability Group),以及配置过程中遇到的坑的填充方法. 目前在Linux上可以搭 ...

  9. WCF全局异常处理

    在用wcf做为单纯的服务端的时候,发生错误是常有的事情,特别是在调用其他系统提供的接口的时候,发生的一些错误总是让人摸不着头脑,严重影响了错误的定位.做.net web开发的时候,我们可以在Globa ...

  10. x86保护模式 控制寄存器和系统地址寄存器

    控制寄存器和系统地址寄存器 控制寄存器    crx cr0   指示cpu工作方式的控制位  包含启用和禁止分页管理机制的控制位  包含控制浮点协处理器操作的控制位   注意必须为0的位 cr2和c ...