Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Get: Should return typed nil when out is nil/empty slice #106

Comments

@mattayes
Copy link

mattayes commented Dec 17, 2020

I'm running into an issue when using Get() with a zero-value or empty slice of structs.

Here's an example:

package main

import (
	"fmt"
	"log"

	"github.com/thoas/go-funk"
)

type BigThing struct {
	Littles []LittleThing
}

type LittleThing struct {
	SomeKey string
}

func main() {
	// Using a zero-value slice (unexpected output)
	var x BigThing
	iKeys := funk.Get(x.Littles, "SomeKey")
	if _, ok := iKeys.([]string); ok {
		log.Fatalf("Uh oh...")
	}
	fmt.Printf("iKeys is %T, not []string\n", iKeys)

	// Using an empty slice (unexpected output)
	x.Littles = []LittleThing{}
	iKeys = funk.Get(x.Littles, "SomeKey")
	if _, ok := iKeys.([]string); ok {
		log.Fatalf("Uh oh...")
	}
	fmt.Printf("iKeys is %T, not []string\n", iKeys)

	// Using a non-empty slice (expected output)
	x.Littles = []LittleThing{{SomeKey: "hello"}}
	iKeys = funk.Get(x.Littles, "SomeKey")
	keys, ok := iKeys.([]string)
	if !ok {
		log.Fatalf("Uh oh...")
	}
	fmt.Println(keys)
}

I expected all three cases to return a zero-value []string (i.e., a typed nil), however the first two return an untyped nil, which causes these type conversions to fail.

vellotis added a commit to vellotis/go-funk that referenced this issue Mar 10, 2021
@vellotis vellotis mentioned this issue Mar 10, 2021
thoas added a commit that referenced this issue Mar 11, 2021
@mattayes
Copy link
Author

Thanks @vellotis! Thanks @thoas!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment