专栏名称: 狗厂
目录
相关文章推荐
触乐  ·  恐怖游戏苦手丨触乐怪话 ·  2 天前  
九派新闻  ·  《黑神话:悟空》PS5国行版获批 ·  2 天前  
九派新闻  ·  《黑神话:悟空》PS5国行版获批 ·  2 天前  
游戏茶馆  ·  3个月内狂澜2个亿,这个超级缝合怪赚麻了 ·  2 天前  
触乐  ·  《双影奇境》的光彩与瑕疵丨触乐 ·  4 天前  
游戏茶馆  ·  预亏22亿,中手游一把亏完近8年利润 ·  2 天前  
51好读  ›  专栏  ›  狗厂

【英】Go结构体的标注函数

狗厂  · 掘金  ·  · 2018-06-01 06:06

正文


Go Struct (Callout) Functions

Go struct Callout functions are a powerful way to create highly configurable, easily testable, future proof structs.

This article should provide a brief overview of what struct Callout functions are, how they work, and when they might be useful. I recently answered a question asking about this , and have been seeing this pattern in many projects including the standard library , and I really haven’t seen much written about it.

Struct Functions or “Callout” functions are powerful tool which provide a flexible configurable struct, and allow multiple implementations or functional options. Abstracting to a callout function can future proof a specific slice of functionality by defining a clear relationship between a structure and a functional dependency. Once this functional dependency is defined it allows for different implementations to be provided. It is very similar to hiding a dependency behind an interface but is a much smaller scope, as it is only a single function, instead of an interface with potentially multiple methods.

I have found go struct Callout functions to be a powerful way to introduce a “seam” into a go struct in order to provide multiple implementations. Using a Callout function allows an alternative implementation to be provided during testing.

Consider a car struct that offers an outside temperature dashboard reading.

The outside temperature gauge is a common on dashboards the car “owns” but may not be directly dependent on the state of the car.

Configurable Implementations

The callout function above allows us to offer many different implementations without having to change anything but the car struct initialization. The following will walk through how a different Callout function implementation can be configured for a variety of different contexts:

Production

Let’s imagine that we have a car company that offers a built in thermometer as a standard offering.

Now in the public initialization of car the thermometer can be configured and used to get the temp reading.

Test







请到「今天看啥」查看全文