3 ms·
"A possible exception can be made for things like int, but even then I prefer defining type aliases for things as much as possible, so the type system is as hel
by jesstaa 12y ago
"A possible exception can be made for things like int, but even then I prefer defining type aliases for things as much as possible, so the type system is as helpful as possible."
It's important to note that Go doesn't allow you to define type aliases. Embedding is the closest you get.
- TheDong 12y agoWhat do you mean? Isn't this a type alias: http://play.golang.org/p/J2gHol1Egd http://play.golang.org/p/J2gHol1Egd When I say "type MyInt int" didn't I just type-alias int? Edit: I'm aware that they're not able to be used interchangeably, but I think I've heard the term used in this context before. I think I'm actually incorrect here and have just heard people use an incorrect term and thought that was an actual go term for some malformed type alias.
- deleted 12y ago[deleted]
- evmar 12y agoGrandparent is correct. You didn't make an alias, because it's not interchangable: http://play.golang.org/p/fiz0NnduNF http://play.golang.org/p/fiz0NnduNF (try running it)
- jesstaa 12y agoIt's not an alias, it's a new type. eg. http://play.golang.org/p/bXgryxNT0H http://play.golang.org/p/bXgryxNT0H
- colin_mccabe 12y agoWhen I say "type MyInt int" didn't I just type-alias int? No, you created a new type. cmccabe@keter:~/tmp> cat inta.go package main import "fmt" type myfoo int func printint(i int) { fmt.Printf("i = %d\n", i) } func main() { var foo myfoo printint(foo) } cmccabe@keter:~/tmp> go build inta.go # command-line-arguments ./inta.go:13: cannot use foo (type myfoo) as type int in argument to printint You are probably thinking about "typedef" in C++, but go works differently in this case.
- Jayschwa 12y agoI would not consider your example to be one of a "type alias". Alias usually means that the names can be used interchangeably without a difference in behavior (i.e. casting). Go actually has some built-in aliases where this is the case. "byte" is an alias for "uint8". They can be used interchangeably. Here is an example of the distinction: http://play.golang.org/p/ukYCBqFeW_ http://play.golang.org/p/ukYCBqFeW_
- jerf 12y agoCorrect. I will fix that when I'm no longer traveling.