首页 > 其他分享 >go判断实现接口的方法 var _ Interface = (*Type)(nil)

go判断实现接口的方法 var _ Interface = (*Type)(nil)

时间:2024-03-27 14:55:20浏览次数:17  
标签:nil int type fmt 接口 var Interface Type

阅读源码过程中发现很多var _ Interface = (*Type)(nil)写法,对于接口实现情况的判断十分优雅,而自己编写代码过程中鲜有涉及。

var _ InnerObjectWithSelector = (*PodChaos)(nil)
var _ InnerObject = (*PodChaos)(nil)

其作用就是用来检测*Type是否实现了Interface接口,有多种形式,具体见代码
这种定义方式主要用于在源码编译的时候检测预期的接口是否被实现,未实现将导致编译失败,并可提示缺少了哪些方法的实现

package main

import (
	"fmt"
	"reflect"
)

type I interface {
	Foo()
}

type T struct{}
type F struct{}

func (t T) Foo() {} // 注释掉编译将报错 cannot use (*T)(nil) (type *T) as type I in assignment: *T does not implement I (missing Foo method)

// 判断*T是否实现了IA接口,未实现编译时将报错
var _ I = (*T)(nil) // 将nil转为*T类型后判断是否实现I接口
var _ I = &T{}
var _ I = new(T)

// 判断T是否实现了IA接口,未实现编译时将报错
var _ I = T{}

func main() {
	// _ = []int([]int64{}) // cannot convert []int64{} (type []int64) to type []int

	// 可被定义为nil的类型,将nil转换为这些类型
	n1 := (*struct{})(nil) // 指针
	fmt.Printf("(*struct{})(nil) nil: %t ,type is: %s\n", n1 == nil, reflect.TypeOf(n1).String())

	n2 := []int(nil)      // 切片
	fmt.Printf("[]int(nil) nil: %t ,type is: %s\n", n2 == nil, reflect.TypeOf(n2).String())

	n3 := map[int]bool(nil) // map
	fmt.Printf("map[int]bool(nil) nil: %t ,type is: %s\n", n3 == nil, reflect.TypeOf(n3).String())

	n4 := chan string(nil) // channel
	fmt.Printf("chan string(nil) nil: %t ,type is: %s\n", n4 == nil, reflect.TypeOf(n4).String())

	n5 := (func())(nil) // 函数
	fmt.Printf("(func())(nil) nil: %t ,type is: %s\n", n5 == nil, reflect.TypeOf(n5).String())

	n6 := interface{}(nil) // 接口,可任意赋值
	fmt.Printf("interface{}(nil) nil: %t \n", n6 == nil)

	// 下面这些行跟上面的等价
	var _ *struct{} = nil
	var _ []int = nil
	var _ map[int]bool = nil
	var _ chan string = nil
	var _ func() = nil
	var _ interface{} = nil

	// 报错 use of untyped nil
	// var _ = nil
}

标签:nil,int,type,fmt,接口,var,Interface,Type
From: https://www.cnblogs.com/aiverhua/p/18099213

相关文章

  • 前端学习-TypeScript菜鸟教程-002-TypeScript基础知识
    菜鸟教程链接基本是阅读教程,记笔记大部分为直接复制基础类型any,number,string,boolean,数组(如letx:number[]=[1,2]或letx:Array<number>=[1,2]),元组(letx:[string,number])enumenumColor{Red,Green,Blue};letc:Color=Color.Blue;void:用于标识方......
  • FUSB302BMPX 可编程USB芯片控制器 接口集成电路 302B Type-C Control IC with PD
    FUSB302BMPX是一种可编程的USBType-C控制器,由安森美半导体公司生产。它支撑USBType-C检测,包含衔接和方向,并集成了USBBMC功率输送协议的物理层,可完成高达100W的电源和角色交换。该控制器适用于希望完成DRP/SRC/SNKUSBType-C衔接器的系统规划人员。此外,FUSB302BMPX支撑USB3......
  • TypeScript日期方法封装
    TypeScript日期方法封装1.获取当前日期,格式YYYY-MM-DD2.获取当前时间,格式YYYY-MM-DDHH:mm:ss3.返回一年的总天数4.返回日期是当年第多少天5.返回时间范围的所有周末6.返回该日期的周末日期7.返回时间范围的各个月份的总天数8.返回日期范围内所有周末,一级前......
  • FreeType编译与使用
    FreeType是一款免费用于渲染字体的开源库。在使用该类库时,最好先过一遍官方文档,其中FreeTypeGlyphConventions部分的文章必读。编译我们可以进入下载界面,点击任意一个地址下载源码。这里笔者使用的是2.13.2版本,解压后会获得一个freetype-2.13.2文件夹。进入目录freetype-2.......
  • java用es报错ElasticsearchStatusException[Elasticsearch exception [type=x_content
    java报错ElasticsearchStatusException[Elasticsearchexception[type=x_content_parse_exception,reason=[1:55][bool]failedtoparsefield[must]]];nested:ElasticsearchException[Elasticsearchexception[type=parsing_exception,reason=[match]unknowntoke......
  • typestack/class-validator
    typestack/class-validatorPublicNotificationsFork 756 Star 10.4k CodeIssues217Pullrequests29DiscussionsActionsSecurityInsights typestack/class-validator   develop4 Branches25 Tags  Code......
  • 前端学习-TypeScript-001-了解、安装TypeScript
    菜鸟教程链接TypeScript简介TypeScript是JavaScript的超集,扩展了JavaScript的语法,因此现有的JavaScript代码可与TypeScript一起工作无需任何修改,TypeScript通过类型注解提供编译时的静态类型检查。TypeScript可处理已有的JavaScript代码,并只对其中的TypeScript......
  • TypeScript学习笔记之泛型
    介绍软件工程中,我们不仅要创建一致的定义良好的API,同时也要考虑可重用性。组件不仅能够支持当前的数据类型,同时也能支持未来的数据类型,这在创建大型系统时为你提供了十分灵活的功能。在像C#和Java这样的语言中,可以使用泛型来创建可重用的组件,一个组件可以支持多种类型的数据......
  • 【黑马店铺】shopType 黑马点评商铺类型缓存作业
    详情见以下代码,注释有详细说明@ServicepublicclassShopTypeServiceImplextendsServiceImpl<ShopTypeMapper,ShopType>implementsIShopTypeService{@ResourceprivateStringRedisTemplatestringRedisTemplate;@OverridepublicResultqueryTyp......
  • No qualifying bean of type 'XXX' available:expected at least 1 bean which qualif
    一项目启动报,Noqualifyingbeanoftype'XXX'available:expectedatleast1beanwhichqualifiesasautowirecandidate翻译为:没有类型为“XXX”的合格bean可用:应至少有1个bean符合autowire候选者的条件排查步骤如下:(1)项目启动类上是否有扫描到该bean下的包(2)如果用......