Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I create an alias of a type in Golang?

Tags:

I'm struggling with my learning of Go.

I found this neat implementation of a Set in go: gopkg.in/fatih/set.v0, but I'd prefer naming my sets with a more explicit name that set.Set, doing something like:

type View set.Set 

In essence, I want my View type to inherit set.Set's methods. Because, well, View is a set.Set of descriptors. But I know Go is pretty peaky on inheritance, and typing in general.

For now I've been trying the following kinda inheritance, but it's causing loads of errors when trying to use some functions like func Union(set1, set2 Interface, sets ...Interface) Interface or func (s *Set) Merge(t Interface):

type View struct {     set.Set } 

I'd like to know if there's a way to achieve what I want in a Go-like way, or if I'm just trying to apply my good-ol' OO practices to a language that discards them, please.

like image 244
Adrien Luxey Avatar asked Oct 17 '16 12:10

Adrien Luxey


People also ask

How do I create a type in Golang?

Structs are the only way to create concrete user-defined types in Golang. Struct types are declared by composing a fixed set of unique fields. Structs can improve modularity and allow to create and pass complex data structures around the system.

Is type a keyword in Golang?

In Go, we can define new types by using the following form. In the syntax, type is a keyword.

What is custom type Golang?

To define a custom type declaration in Golang, use the type keyword. Let's create a new file inside your folder called hello.go and add the following code. /* hello.go */ package main import "fmt" func main() { apps := []string{"Facebook", "Instagram", "WhatsApp"} for i, app := range apps { fmt.Println(i, app) } }

Does Golang have types?

It provides several built-in types such as string, bool, int and float64. Go supports composite types such as array, slice, map and channel. Composite types are made up of other types – built-in types and user-defined types.


1 Answers

If anyone else is coming back to this question, as of Go 1.9 type aliases are now supported.

A type alias has the form: type T1 = T2

So in your example you can just do type View = set.Set and everything will work as you want.

like image 200
Jack Avatar answered Oct 07 '22 07:10

Jack