Blank identifier used for making sure struct implements interface

109 阅读1分钟

Blank identifer can be used to ignore some of mutiple return values of a function, this is the common use case, besides it can also be used to make sure a struct has implemented an interface,

package main

import (
	"fmt"
	"reflect"
)

type Sortable interface {
	Sort()
}

type Sortable2 interface {
	Sort()
}

type MyStruct struct {
}

func (m MyStruct) Sort() {}

var _ Sortable = (*MyStruct)(nil)

func main() {
	var m Sortable
	m = MyStruct{}
	fmt.Println(reflect.TypeOf(m))
}

This line of code var _ Sortable = (*MyStruct)(nil) is used to make sure MyStruct has implemented the interface Sortable. The go-redis framework also has used this in pipeline implementation,

type Pipeliner interface {
	StatefulCmdable
	Do(args ...interface{}) *Cmd
	Process(cmd Cmder) error
	Close() error
	Discard() error
	Exec() ([]Cmder, error)
}

var _ Pipeliner = (*Pipeline)(nil)

// Pipeline implements pipelining as described in
// http://redis.io/topics/pipelining. It's safe for concurrent use
// by multiple goroutines.
type Pipeline struct {
	statefulCmdable

	exec pipelineExecer

	mu     sync.Mutex
	cmds   []Cmder
	closed bool
}