[generics] Embedding interfaces

148 views
Skip to first unread message

Viet Nguyen

unread,
May 7, 2021, 2:08:33 PM5/7/21
to golang-nuts
Hi,

I'm trying to convert this code to use generics:

type Cache interface {
GetIfPresent(interface{}) (interface{}, bool)
}

type LoadingCache interface {
Cache
Get(interface{}) (interface{}, error)
}

However, I couldn't find any way to include Cache[K, V] in LoadingCache[K, V]. (No similar use cases in the proposal? I must miss something here). The workaround is copying all methods over, like:

type Cache[K comparable, V any] interface {
GetIfPresent(K) (V, bool)
}

type LoadingCache[K comparable, V any] interface {
GetIfPresent(K) (V, bool) // FIXME: Embedding the Cache interface
Get(K) (V, error)
}


Is it possible to have something like "interface LoadingCache<K,V> extends Cache<K,V>" as in Java?

Regards,
Viet

Ian Lance Taylor

unread,
May 8, 2021, 9:41:29 AM5/8/21
to Viet Nguyen, golang-nuts
On Fri, May 7, 2021 at 11:08 AM Viet Nguyen <afe...@gmail.com> wrote:
>
> I'm trying to convert this code to use generics:
>
> type Cache interface {
> GetIfPresent(interface{}) (interface{}, bool)
> }
>
> type LoadingCache interface {
> Cache
> Get(interface{}) (interface{}, error)
> }
>
> However, I couldn't find any way to include Cache[K, V] in LoadingCache[K, V]. (No similar use cases in the proposal? I must miss something here). The workaround is copying all methods over, like:
>
> type Cache[K comparable, V any] interface {
> GetIfPresent(K) (V, bool)
> }
>
> type LoadingCache[K comparable, V any] interface {
> GetIfPresent(K) (V, bool) // FIXME: Embedding the Cache interface
> Get(K) (V, error)
> }
>
> // See: https://go2goplay.golang.org/p/T7h15CdUEa3
> // WIP: https://github.com/goburrow/cache/tree/go2

The go2go tool is an experiment and it does not support all valid
code. It's particularly bad at embedding. In the real release it
should work to write

type LoadingCache[K comparable, V any] interface {
Cache[K, V]
Get(K) (V, error)
}

Ian

Viet Nguyen

unread,
May 8, 2021, 10:14:42 AM5/8/21
to Ian Lance Taylor, golang-nuts
Awesome. Thanks muchly
Reply all
Reply to author
Forward
0 new messages