How can I write a function that takes either one of many types in go? - go

I'm trying go for a small project and tried to write these functions:
func fatal(reason string) {
println(reason)
os.Exit(1)
}
func fatal(err error) {
fatal(err.Error())
}
After digging about a bit and finding this answer, which referenced the docs on overloading I realised that what I was trying to do was illegal in go.
What I want is a simple api that allows me to call fatal with either a string or an error in order to simplify my logic. How do I achieve this or a similar goal?
It would feel inelegant to have func fatal(reason string) along with func fatalErr(err error), is that what's needed? Am I missing a different feature of the language that allows me to do what I want?

The most common way to do this would be to define the method as func fatal(err interface{}) then do type assertions or use a type switch within it's body to handle each of the different types. If I were coding for your example it would look like this;
func fatal(err interface{}) {
if v, ok := err.(string); ok {
fmt.Println(v)
}
if v, ok := err.(error); ok {
fmt.Println(v.Error())
} else {
// panic ?
}
}
Also; here's a quick read about type switches and assertions that may be helpful; http://blog.denevell.org/golang-interface-type-assertions-switch.html
You can also check out effective-go as it has sections on both features.

Use log.Fatal() instead. https://golang.org/pkg/log/#Fatal
You can use interface{} but it is not recommended because you lose all the benefits of type checking when you do that. The Go authors get to use interface{} because they understand the appropriate level of additional testing and checks to do when using interface{}. It's much easier (even for intermediate and advanced gophers) to use builtin and standard library functions when something like this is required.
Go does not have algebraic or/sum types either. The standard workaround is to define an and/product type with pointers (e.g. struct{*string, *error}) and go to the effort of making sure you only ever make one of the fields non nil at any point in time.

Function overloading is not supported in the language. From the official Golang site it says,
Method dispatch is simplified if it doesn't need to do type matching as well. Experience with other languages told us that having a variety of methods with the same name but different signatures was occasionally useful but that it could also be confusing and fragile in practice. Matching only by name and requiring consistency in the types was a major simplifying decision in Go's type system.
Regarding operator overloading, it seems more a convenience than an absolute requirement. Again, things are simpler without it.
https://golang.org/doc/faq#overloading
One potential solution would be to define a high level function that type checks and handles different types similarly to how you would overload multiple functions. See #evanmcdonnal's solution for a great example.

Related

Ways to avoid stuttering in go package and struct names?

I have been doing a bit of go programming of late and while trying to follow Effective Go style guidelines, I sometimes find it difficult to avoid stuttering when naming packages and interfaces and structs.
As an example.
I might have a console package with a Console.go file containing a Console interface a console struct and a New function.
//console/Console.go
package console
type Console interface {
Print(s String)
}
type console struct {
....
}
func (c *console) Print(s String){
....
}
func New() Console{
return &console{}
}
Now when I use this somewhere I end up using a console.Console type everywhere.
When I have two or more structs in a package I end up things like
con := console.NewConsole()
I don't mind having large mostly flat package structures but I do like to keep my code organized as much as possible. I am ok with the idea of IO.Reader and IO.Writer but what to do when the package is the same as the thing but still needs to be separated. (Yes I am aware that the given example could be Console.Writer but lets pretend its something completely different)
So my questions are:
Is this stutter effect something I should even worry about? (ie. Is it bad form?)
Does anyone have any tips in avoiding it?
Stuttering type names are generally fine - it's not unusual to have a foo.Foo, because package foo is dedicated to defining type Foo. There's absolutely nothing wrong with that.
What you want to avoid is unnecessary stuttering; this would be things like foo.NewFoo when simply foo.New is sufficiently precise, or foo.FooBar and foo.FooBaz where foo.Bar and foo.Baz would work just as well.
Consider the standard library's html/template, which defines a type (template.Template) and a constructor (template.New).

Any idiomatic generate/preprocessing solution library?

I really like Go but makes me crazy about if-err hell and when I have sync datatypes in Go code with other languages. For C/C++ I can easily deal such stuff with macros, while Go developers say the idiomatic solution for Go is code generation, but I didn't find any out-of-the-box solution.
So basically, what I need is something like
Read the source, for every type usage check if it is listed in special config file. If it is, then change it with the one from config.
Read the source, for every function check if it is listed in config file. If it is then, change it with the code snippet from config by template and add neccessary import if it's missing.
Probably, add some polymorphism based on return values to prevent type casts.
Maybe, add (err error) logic. Not sure it's a good idea.
Like this
code.go
func getConn(id platform.UUID) (res1 string, res2 platform.res) {
res1 = driver_native_res(id)
res2 = driver_native_res(id)
return
}
code-gen.go
import (
"linux"
)
func getConn(id uint64) (res1 string, res2 int32, err error) {
res1, err = linux.GetResAsString(id)
if err != nil {
return
}
res2, err = linux.GetRes(id)
if err != nil {
return
}
return
}
I know about go AST, but seems like it's not very fast to implement such features with it. I hope there is some easier solution.
As you have discovered, there are no macros and are unlikely to be. There may be generics at some point which could be helpful. In the meantime, there are a few options for code generation. You can use go generate for this:
// add a magic comment to your go file
// which needs some extra generated code
// this calls a tool called stringer to generate,
// but it could be yacc or some homemade tool.
//go:generate stringer -type=Pill
// call go generate to generate the methods:
go generate
https://blog.golang.org/generate
But it really requires you to have a tool to generate the code you want like stringer.
Or you could just use text/template, build your own template, and run a simple tool that substitutes values into this template (from a config file, or perhaps arguments on the command line).
mytool generate -type=thing -field=type...
... mytool loads a tmplate file,
runs it through text/template and outputs it.
This is pretty straightforward and you could easily build a custom system with it, though you'll probably want to generate once, then use the code. Here are some examples of this approach:
http://clipperhouse.github.io/gen/
https://github.com/fragmenta/fragmenta
Finally, you can use tools like grpc which generate structs in multiple languages in order to ease cross-language communication, which sounds like exactly the use case you are looking for:
https://grpc.io/docs/quickstart/go.html
I'd look at something like grpc first.

Finding functions that return a specific type

Perhaps this is a silly question, but is there a way to find all functions (in the standard library or GOPATH) that return a specific type?
For example there are many functions that take io.Writer as an argument. Now I want to know how to create an io.Writer and there are many ways to do so. But how can I find all the ways easily without guessing at packages and looking through all the methods to find those that return an io.Writer (or whatever other type I'm after)?
Edit: I should extend my question to also find types that implement a specific interface. Sticking with the io.Writer example (which admittedly was a bad example for the original question) it would be good to have a way to find any types that implement the Writer interface, since those types would be valid arguments for a function that takes takes an io.Writer and thus answer the original question when the type is an interface.
Maybe not the best way but take a look at the search field at the top of the official golang.org website. If you search for "Writer":
http://golang.org/search?q=Writer
You get many results, grouped by categories like
Types
Package-level declarations
Local declarations and uses
and Textual occurrences
Also note that io.Writer is an interface, and we all know how Go handles interfaces: when implementing an interface, there is no declaration of intent, a type implicitly implements an interface if the methods defined by the interface are declared. This means that you won't be able to find many examples where an io.Writer is created and returned because a type might be named entirely different and still be an io.Writer.
Things get a little easier if you look for a non-interface type for example bytes.Buffer.
Also in the documentation of the declaring package of the type the Index section groups functions and methods of the package by type so you will find functions and methods of the same package that return the type you're looking for right under its entry/link in the Index section.
Also note that you can check the dependencies of packages at godoc.org. For example you can see what packages import the io package which may be a good starting point to look for further examples (this would be exhausting in case of package io because it is so general that at the moment 23410 packages import it).
In my days coding I'm personally rare in need to find functions returning Int16 and error(func can return few values in Go, you know)
For second part of your question there exists wonderful cmd implements written by Dominik Honnef go get honnef.co/go/implements
After discover type that satisfy your conditions you can assume constructor for type (something like func NewTheType() TheType) would be just after TheType declaration in source code and docs. It's a proven Go practice.

How to get all defined types?

package demo
type People struct {
Name string
Age uint
}
type UserInfo struct {
Address string
Hobby []string
NickNage string
}
another package:
import "demo"
in this package, how can I get all the types exported from the demo package?
Using go/importer:
pkg, err := importer.Default().Import("time")
if err != nil {
fmt.Println("error:", err)
return
}
for _, declName := range pkg.Scope().Names() {
fmt.Println(declName)
}
(note, this returns an error on the Go Playground).
Go retains no master list of structs, interfaces, or variables at the package level, so what you ask is unfortunately impossible.
Drat, I was hoping that Jsor's answer was wrong, but I can't find any way to do it.
All is not lost though: If you have the source to 'demo', you could use the parser package to fish out the information you need. A bit of a hack though.
Do you come from some scripting language? It looks so.
Go has good reasons to propagate to let not slip 'magic' into your code.
What looks easy at the beginning (have access to all structs, register them automatically somewhere, "saving" coding) will end up in debugging and maintenance nightmare when your project gets larger.
Then you will have to document and lookup all your lousy conventions and implications.
I know what I am talking about, because I went this route several times with ruby and nodejs.
Instead, if you make everything explicit you get some feature, like renaming the People struct to let
the compiler tell you where it is used in your whole code base (and the go compiler is faster than you).
Such possibilities are invaluable for debugging, testing and refactoring.
Also it makes your code easy to reason about for your fellow coders and yourself several months after you have written it.

Can I define C functions that accept native Go types through CGo?

For the work I'm doing to integrate with an existing library, I ended up needing to write some additional C code to provide an interface that was usable through CGo.
In order to avoid redundant data copies, I would like to be able to pass some standard Go types (e.g. Go strings) to these C adapter functions.
I can see that there are GoString and GoInterface types defined in the header CGo generates for use by exported Go functions, but is there any way to use these types in my own function prototypes that CGo will recognise?
At the moment, I've ended up using void * in the C prototypes and passing unsafe.Pointer(&value) on the Go side. This is less clean than I'd like though (for one thing, it gives the C code the ability to write to the value).
Update:
Just to be clear, I do know the difference between Go's native string type and C char *. My point is that since I will be copying the string data passed into my C function anyway, it doesn't make sense to have the code on the Go side make its own copy.
I also understand that the string layout could change in a future version of Go, and its size may differ by platform. But CGo is already exposing type definitions that match the current platform to me via the documented _cgo_export.h header it generates for me, so it seems a bit odd to talk of it being unspecified:
typedef struct { char *p; int n; } GoString;
But there doesn't seem to be a way to use this definition in prototypes visible to CGo. I'm not overly worried about binary compatibility, since the code making use of this definition would be part of my Go package, so source level compatibility would be enough (and it wouldn't be that big a deal to update the package if that wasn't the case).
Not really. You cannot safely mix, for example Go strings (string) and C "strings" (*char) code without using the provided helpers for that, ie. GoString and CString. The reason is that to conform to the language specs a full copy of the string's content between the Go and C worlds must be made. Not only that, the garbage collector must know what to consider (Go strings) and what to ignore (C strings). And there are even more things to do about this, but let me keep it simple here.
Similar and/or other restrictions/problems apply to other Go "magical" types, like map or interface{} types. In the interface types case (but not only it), it's important to realize that the inner implementation of an interface{} (again not only this type), is not specified and is implementation specific.
That's not only about the possible differences between, say gc and gccgo. It also means that your code will break at any time the compiler developers decide to change some detail of the (unspecified and thus non guaranteed) implementation.
Additionally, even though Go doesn't (now) use a compacting garbage collector, it may change and without some pinning mechanism, any code accessing Go run time stuff directly will be again doomed.
Conclusion: Pass only simple entities as arguments to C functions. POD structs with simple fields are safe as well (pointer fields generally not). From the complex Go types, use the provided helpers for Go strings, they exists for a (very good) reason.
Passing a Go string to C is harder than it should be. There is no really good way to do it today. See https://golang.org/issue/6907.
The best approach I know of today is
// typedef struct { const char *p; ptrdiff_t n; } gostring;
// extern CFunc(gostring s);
import "C"
func GoFunc(s string) {
C.CFunc(*(*C.gostring)(unsafe.Pointer(&s)))
}
This of course assumes that Go representation of a string value will not change, which is not guaranteed.

Resources