golang 接口

接口

一组method 签名的组合 通过interface 来定义对象的一组行为
interface 就是一组抽象方法的集合

interface 类型

interface 类型定义了一组方法, 如果某个对象实现了某个接口中的方法, 则此对象就实现了此接口

interface 值

如果定义了一个interface 变量, 那么这个变量里面可以存实现这个interface的任意类型的对象。

空interface

interface{} 不包含任何的method
所有的类型都实现了空的interface

空interface 可以用来存储任意类型的值
一个函数把interface{} 作为参数 可以接受任意类型的值作为参数, 如果一个函数返回interface{ 那么也就可以返回任意类型的值

interface 变量存储的类型

interface 变量中国可以存储任意类型对象的数值(前提是实现了 interface)
反过来要想通过这个变量里面 实际保存的是哪个类型的对象呢 ?

  1. 断言 comma-ok 断言

    value, ok = element.(T)
    value 变量的值,ok 是bool 类型, element 是 interface 变量, T 是断言的类型
    如果element 里面确实存储了T 类型的数值, 那么ok 返回true 否则false

package main

	import (
		"fmt"
		"strconv"
	)

	type Element interface{
   }
	type List [] Element

	type Person struct {
   
		name string
		age int
	}

	//定义了String方法,实现了fmt.Stringer
	func (p Person) String() string {
   
		return "(name: " + p.name + " - age: "+strconv.Itoa(p.age)+ " years)"
	}

	func main() {
   
		list := make(List, 3
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值