1

I understand how to use multiple return values in go. I further understand that in most cases one of the returns is an error, so ignoring returned values can be dangerous.

Is there a way to ignore a value in struct initializer like this? The below example does not work as Split returns two values, but I am interested only in the first one. I can of course create a variable but...

someFile := "test/filename.ext"

contrivedStruct := []struct{
    parentDir string
}{
    { parentDir: filepath.Split(someFile) },
}
Grzegorz Żur
  • 47,257
  • 14
  • 109
  • 105
mikijov
  • 1,552
  • 24
  • 37
  • 1
    There is no function Split in package os. – Grzegorz Żur Feb 02 '18 at 23:00
  • 2
    @GrzegorzŻur maybe this is supposed to be [`filepath.Split`](https://golang.org/pkg/path/filepath/#Split)? – Adam Smith Feb 02 '18 at 23:12
  • 2
    For your example you could use filepath.Dir(someFile). Or you could use an intermediary function, `func F(s string) string { p, _ := filepath.Split(s); return p }` – jrefior Feb 02 '18 at 23:27
  • 1
    Related / possible duplicates: [Go: multiple value in single-value context](https://stackoverflow.com/questions/28227095/go-multiple-value-in-single-value-context/28233172#28233172); and [Return map like 'ok' in Golang on normal functions](https://stackoverflow.com/questions/28487036/return-map-like-ok-in-golang-on-normal-functions/28487270#28487270). – icza Feb 03 '18 at 11:28

2 Answers2

2

It's not possible to use only one of the return values when initializing members in Go.

Using variables clearly expresses your intent.

Go sometimes feels like it could be more succinct, but the Go authors favoured readability over brevity.

Alternatively, use a wrapper function. There are several 'Must' wrapper functions in the standard library, like: template.Must.

func first(args ...string) string {
    return args[0]
}

For your particular example, splitting paths, see filepath.Base or filepath.Dir.

Mark
  • 6,731
  • 1
  • 40
  • 38
  • Thanks for the wrapper funciton suggestion. It's a valid alternative if I have to repeat a lot of initialization. – mikijov Feb 03 '18 at 16:46
1

No, there is no way to skip one of the returned values in structure initializer.

Grzegorz Żur
  • 47,257
  • 14
  • 109
  • 105