On 15 Mar 2015 14:29, <dug...@gmail.com> wrote:
>
> Does it change anything if we view this problem this way...
> I have two variables that are both pointers. They both point to the same spot in memory. However, 'go' thinks that pointer 1 points to something of type 'Base' while pointer 2 points to something of type 'Extend'. Is there any way to convert *Base to *Extend ?
>
You can't do this in Go. You can't have two pointers to the same object disagree about it's type. Objects only have one type.
You can embed Base in Extend and access the fields of Base. There is no way to get to Extend from a pointer to the embedded Base unless the Base itself contains that pointer.
Go doesn't provide inheritance behaviour but you can fake a lot of it with embedding and manually adding your own parent pointers to your embedded types. But if you're doing this then you're fighting the language and won't have a great time.
On 16 Mar 2015 00:47, "Doug Davis" <dug...@gmail.com> wrote:
>
> So, this is really all about the UX of the user of MyStruct. I’m sure there are ways to get the net result that I want, but I’m trying to make the user of MyStruct’s life as easy as possible, which would normally mean calls like:
> me = &MyStruct{ … }
> me.Name = “John”
> me.Set( “Name”, “John” )
> me.Save()
>
Code reuse in Go is done by having types implement interfaces and having reusable functions that take those interfaces as parameters.
Code reuse in Java or C++ is more commonly done through inheritance, Go code isn't written like that.
Instead of having your types know how to save() themselves, instead you have a save() function that knows how to save any type that implements an interface.
It's just as easy to call some database.Save(someValue) as it is to call someValue.save().
The database.Save() version would be able to save any type that implemented the interface it expected, even if that type didn't know about your Base type. Could be implemented by non struct types that don't have fields or be a wrapper for another interface type. Eg. A wrapper for an io.Reader that reads json from a stream and makes it available for saving.
The Go style leads to more code duplication in places where inheritance would reduce duplication but less duplication in other areas so it balances out.
Eg. Should a save() method return an error? You'd need to decide this in your Base type. But some saving might not be able to result in errors, like saving to a in memory database. So database.Save(someValue) might need error handling, but memoryDatabase.save(someValue) wouldn't.