I’m just starting with Go after not touching real programming for a vastly long time. I’m trying to create a function where you pass in an integer and it returns a different struct based on that integer.
I’m not sure if this is even possible, and I’ve tried passing back pointers as well, and still no go. I’m getting a weird compilation error as well on that function that I don’t see why it’s failing.
I just need a hint here of what’s happening and how do I achieve what I need. Are functions even the right way of doing that? Should I be using methods or interfaces for that?
I’ve tried conversion. Getting an error.
It doesn’t seem possible to just assign the pointer of one global struct to another either.
Something like: *csvdata{} := *CSVdataDB1{} doesn’t work.
Nothing is dropped, the full result is as expected, it’s the zero value of that struct.
You’ll have a lot less trouble and you will fight the language a lot less, if you create a common interface or completely separate codepathes for dealing with each type.
Thanks Nobbz! Part of my problem seems that the reflection in the gocsv package I’ve been using is broken. So it can’t reflect back to the struct from the interface. Great learning experience though.
I’ll look at rewriting my code, as I drop the gocsv package…
I should probably clarify. I did get it working, but the gocsv package looses the struct tags. It’s the gocsv package that’s broken: https://github.com/gocarina/gocsv/issues/89
I mean the field identifiers in your struct. You have them with lowercase names, so nothing from outside of your package can see the fields. You need to write them with a Capital letter to make them visible and accessible.
You mean they are dropped then the CSV functions is using the struct? I have no experience with reading CSV with go but if it works in a similar way as Json for example must you use uppercase fieldnames so they are exported and another package can read them.
Yes, it’s similar, but the uppercase fieldnames made no difference, there’s a bug in the package.
Anyway, I used the CSVReader method directly from that package and forwent using their marshaling methods and the structs. It’s not as nice, but things are actually simpler that way anyway.
I found one difference with your example and the example in the Readme off the package. In their call to the function they giva a slice of pointers but you send in just one structure. This could be the problem.
clients := []*Client{}
if err := gocsv.UnmarshalFile(clientsFile, &clients); err != nil { // Load clients from file
panic(err)
}
then I read the code does the function used by Unmarshal function readTo start by finding the underlying type of the array or slice.