go interface{}使用
先上代码
func In(haystack []interface{}, needle interface{}) (bool, error) {
sVal := reflect.ValueOf(haystack)
kind := sVal.Kind()
if kind == reflect.Slice || kind == reflect.Array {
for i := 0; i < sVal.Len(); i++ {
if sVal.Index(i).Interface() == needle {
return true, nil
}
}
return false, nil
}
return false, fmt.Errorf("UnSupportType")
}
func test() {
a := []int{1,2}
b := 3
flag, err := In(a,b) // error, cannot user 'a'(type []int) as type []interface{}
}
为什么会报错?
因为空接口拥有两个指针,内存布局上会占用两个机器字长。
对于长度为n的空接口切片而言,它的每个元素都是以2机器字长为单位的连续空间,因此总共会占用 2n个机器字长的空间。然而对于普通的切片,[]int它的每个元素都是 int 类型的,由于 []int 和 []interface{} 内存布局不同,所以不能直接将 []int 作为 []interface{};
Introduction
Given that you can assign a variable of any type to an interface{}, often people will try code like the following.
var dataSlice []int = foo()
var interfaceSlice []interface{} = dataSlice
This gets the error
cannot use dataSlice (type []int) as type []interface { } in assignment
The question then, "Why can't I assign any slice to an []interface{}, when I can assign any type to an interface{}?"
Why?
There are two main reasons for this.
The first is that a variable with type []interface{} is not an interface! It is a slice whose element type happens to be interface{}. But even given this, one might say that the meaning is clear.
Well, is it? A variable with type []interface{} has a specific memory layout, known at compile time.
Each interface{} takes up two words (one word for the type of what is contained, the other word for either the contained data or a pointer to it). As a consequence, a slice with length N and with type []interface{} is backed by a chunk of data that is N*2 words long.
This is different than the chunk of data backing a slice with type []MyType and the same length. Its chunk of data will be N*sizeof(MyType) words long.
The result is that you cannot quickly assign something of type []MyType to something of type []interface{}; the data behind them just look different.
What can I do instead?
It depends on what you wanted to do in the first place.
If you want a container for an arbitrary array type, and you plan on changing back to the original type before doing any indexing operations, you can just use an interface{}. The code will be generic (if not compile-time type-safe) and fast.
If you really want a []interface{} because you'll be doing indexing before converting back, or you are using a particular interface type and you want to use its methods, you will have to make a copy of the slice.
var dataSlice []int = foo()
var interfaceSlice []interface{} = make([]interface{}, len(dataSlice))
for i, d := range dataSlice {
interfaceSlice[i] = d
}
go interface{}使用的更多相关文章
- angular2系列教程(七)Injectable、Promise、Interface、使用服务
今天我们要讲的ng2的service这个概念,和ng1一样,service通常用于发送http请求,但其实你可以在里面封装任何你想封装的方法,有时候控制器之间的通讯也是依靠service来完成的,让我 ...
- 接口--interface
“interface”(接口)关键字使抽象的概念更深入了一层.我们可将其想象为一个“纯”抽象类.它允许创建者规定一个类的基本形式:方法名.自变量列表以及返回类型,但不规定方法主体.接口也包含了基本数据 ...
- Configure a bridge interface over a VLAN tagged bonded interface
SOLUTION VERIFIED February 5 2014 KB340153 Environment Red Hat Enterprise Linux 6 (All Versions) Red ...
- Create a bridge using a tagged vlan (8021.q) interface
SOLUTION VERIFIED April 27 2013 KB26727 Environment Red Hat Enterprise Linux 5 Red Hat Enterprise Li ...
- Configure a bridged network interface for KVM using RHEL 5.4 or later?
environment Red Hat Enterprise Linux 5.4 or later Red Hat Enterprise Linux 6.0 or later KVM virtual ...
- Set up VLAN (802.1q) tagging on a network interface?
SOLUTION VERIFIED October 13 2015 KB39674 KB741413 environment Red Hat Enterprise Linux 4 Red Hat En ...
- 谨慎使用Marker Interface
之所以写这篇文章,源自于组内的一些技术讨论.实际上,Effective Java的Item 37已经详细地讨论了Marker Interface.但是从整个Item的角度来看,其对于Marker In ...
- 浅析Go语言的Interface机制
前几日一朋友在学GO,问了我一些interface机制的问题.试着解释发现自己也不是太清楚,所以今天下午特意查了资料和阅读GO的源码(基于go1.4),整理出了此文.如果有错误的地方还望指正. GO语 ...
- 如何设计一门语言(七)——闭包、lambda和interface
人们都很喜欢讨论闭包这个概念.其实这个概念对于写代码来讲一点用都没有,写代码只需要掌握好lambda表达式和class+interface的语义就行了.基本上只有在写编译器和虚拟机的时候才需要管什么是 ...
- abstract与interface之房祖名张默版
最近把java基础知识拿出来看看,看到abstract与interface的时候,觉得有点模糊,好像面试官也喜欢问这个问题.我在百度了查了好长时间,觉得讲算比较清楚的是那篇讲 Door,然后想要带个报 ...
随机推荐
- Python可变参数*args和**kwargs
本文我们将通过示例了解 Python函数的可变参数*args和 **kwargs的用法. 知识预备:Python 函数和 Python 函数参数 在Python编程中,我们定义一个函数来生成执行类似操 ...
- asp.net多语言网站的完整解决方案
应用场景:通过前端切换网站使用英语.中文两种语言. 解决思路:ResourceManager会通过当前线程区域性信息,读取对应的Resource文件,从而达到切换语言的效果,其实质是是在切换当前线程的 ...
- SQL Server 2008安全加固手册
1.身份鉴别 1.1避免使用空密码和弱口令 要求:应对登录操作系统和数据库系统的用户进行身份标识和鉴别. 目的:操作系统和数据库系统管理用户身份鉴别信息应具有不易被冒用的特点,口令应有复杂度要求并定期 ...
- Discuz!X系列全版本后台sql注入复现
圈子某位大佬公布的0day,拿来刷一刷,漏洞分析请移步大佬文章.大佬链接 0x01 环境准备 1.首先去码云下载最新版本的discuz(DiscuzX 3.4 R20191201). 2.将upaod ...
- badusb
badusb介绍 BadUSB是利用伪造HID设备执行攻击载荷的一种攻击方式.HID(Human InterfaceDevice)设备通常指的就是键盘鼠标等与人交互的设备,用户插入BadUSB,就会 ...
- systemd --user进程CPU占用高问题分析
1.问题由来 近期发现堡垒机环境有如下问题,systemd占用大量cpu: 原文链接:https://www.cnblogs.com/yaohong/p/16046670.html 2.问题定位 2. ...
- Java 实现汇总排序
排序在系统中经常能用到,一般可以在数据库做排序,也可以在服务端做排序.在数据库一般使用 order by 排序.而服务端也是使用快排.本期使用汇总排序. 问题 统计销售数据,每个销售员都有对应的部门和 ...
- Mybatis useGeneratedKeys无法返回主键解决
1.项目环境--SpringBoot下的SSM+Maven 2.问题出现位置--Dao层和Mapper文件 错误代码如下图: dao层: mapper文件: 错误代码分析: 使用useGenerate ...
- HMS Core定位服务在生活服务类App中可以自动填写收货地址啦
在涉及团购.外卖.快递.家政.物流.搬家等生活服务类的App.小程序中,填写收货地址是用户高频使用的功能.这一功能通常采取让用户手动填写的解决方案,例如上下拉动选择浙江省-->杭州市--> ...
- Python - 数据存储与数据库简介