GV

GeezerVison

The World Wide Web, restored to 800 pixels of glory.

Home|About|Gaming cabinet|Archives|How it works|Starter sites

On this site

  • 北野
  • 首页
  • 文章列表
  • 关于我
  • Twitter
  • Twitter
  • Github
  • Go - 巧用Constraint接口实现约束
  • rpcx - 消息协议
  • Kitex TTHeader协议
  • Thrift THeader协议
  • 妙用Go类型定义避免循环引用
  • 女孩
  • "兄弟"

This view

  • Original page
  • New address

GeezerVison is showing alimy.github.io — 北野 · 那年江湖,遇见你

在Go开发中,通常会使用类似 var _ core.TweetSearchService = (*bridgeTweetSearchServant)(nil) 的语句借助Go编译器在 编译期 检测某个类型是否完全实现了某个接口的所有方法,比如此例, 如果 *bridgeTweetSearchServant 缺失 接口 core.TweetSearchService 的某些方法实现,Go将会在编译期报错,不能成功编译App.

在工程实践中,可以在 包内 将这类 接口实现约束(Constraint) 语句 统一放在 constraint.go 中,并添加 build tag //go:build constraint 使用tag条件编译机制,只有在使用 go build -tags constraint 时才会进行接口实现约束的检测,在编译产品App时就不带 constraint tag,也就不会把这些 只应在开发期有效的语句 编译到最终的App中。

以下是 『paopao-ce』 的一个使用实例:

// file: https://github.com/rocboss/paopao-ce/blob/dev/internal/dao/search/constraint.go

//go:build constraint

package search

import "github.com/rocboss/paopao-ce/internal/core"

var (
	_ core.TweetSearchService = (*bridgeTweetSearchServant)(nil)

	_ core.TweetSearchService = (*meiliTweetSearchServant)(nil)
	_ core.VersionInfo        = (*meiliTweetSearchServant)(nil)

	_ core.TweetSearchService = (*zincTweetSearchServant)(nil)
	_ core.VersionInfo        = (*zincTweetSearchServant)(nil)
)
You are visitor 01402775 — GeezerVison does not store the pages you look up.
Best viewed with Netscape Navigator 4.7 or Internet Explorer 6 at 800×600. No cookies required.