Can you review some points for me ? You return a DataFactory from Get. I suppose you’re trying to implement an abstract factory rather than a factory. If so, why are you trying to return a User ? It’s not a factory. If you want to return multiple possible objects from Get, they should implement an interface or being return as interface{}. Your error comes from the fact that you’re trying to affect the User object to the DataFactory struct …you could return &models.User{} directly by the way. But still there’s a flaw in your design.
To quickly highlight the reason you’re getting an error:
In the User case of the switch statement you have this line:
DataFactory = models.User{}
You have previously defined DataFactory as a type and you’re trying to assign the value of models.User{} to the type DataFactory which is of course isn’t going to work.
You could simply create a new variable and assign it the value of model.User{}.
case "User":
factory := models.User{}
return &factory
I appreciate your time and effort replying to my post. Thanks
Anyway, I want to create a function that accept a model name and return its struct/model, A global function perhaps. Your suggestions are nice, but for example. If I implement an interface, there would be a possible redundancy of models declaration. And the second one is the use of interface{} as a return type. There will be a lost of properties assigned to the specific model.
If I get correctly your idea, your Get function should return different model objects like in the PHP example. In this situation I don’t see an other solution thant the two I’ve explained : an interface or an interface{} then type conversion. I thought of something like this :
package main
type User struct {}
type Purchase struct {}
type DefaultType struct {}
func Get(_type string) interface{} {
switch _type {
case "user":
return &User{}
case "purchase":
return &Purchase{}
default:
return &DefaultType{}
}
}
func main() {
var user User = Get("user").(User)
}
The above solutions works, but why not declare the model directly if that is the case. The reason behind why I’m dealing with this stuff is because, whenever a change in a model name you’ll not look for every declaration of your model inside your code. But anyway, thank you for sharing your solution.
My solution implies you know the type but if you had an interface you could implement differently and you wouldn’t require a cast. I also mentioned this solution but only gave the implementation of the case of interface{} return. How is it useful ? Well, you hide the details of initialization of your user, and you could even provide different initializations chosen by the argument.
But one question is still disturbing me about your initial implementation. How do you expect to return a User object as a DataFactory ? There’s no relation between them and polymorphism exists only with interface.