How to return instance of struct, idiomatic wayHow to define a function type which accepts any number of arguments in Go?How do I convert a go method to a func?Stack vs heap allocation of structs in Go, and how they relate to garbage collectionType converting slices of interfaces in GoWhat is an idiomatic way of representing enums in Go?Removing fields from struct or hiding them in JSON ResponsePointers vs. values in parameters and return valuesWrite struct to csv fileGolang: loop through fields of a struct modify them and and return the struct?Go function types that return structs being used with interfaces
Multi tool use
How does a Swashbuckler rogue "fight with two weapons while safely darting away"?
When did stoichiometry begin to be taught in U.S. high schools?
Stark VS Thanos
How can Republicans who favour free markets, consistently express anger when they don't like the outcome of that choice?
Were there two appearances of Stan Lee?
When and why did journal article titles become descriptive, rather than creatively allusive?
How can I get precisely a certain cubic cm by changing the following factors?
Asahi Dry Black beer can
How to creep the reader out with what seems like a normal person?
What does 「再々起」mean?
Why is the origin of “threshold” uncertain?
Was it really necessary for the Lunar Module to have 2 stages?
Is it possible to Ready a spell to be cast just before the start of your next turn by having the trigger be an ally's attack?
Historically, were women trained for obligatory wars? Or did they serve some other military function?
What's the metal clinking sound at the end of credits in Avengers: Endgame?
"ne paelici suspectaretur" (Tacitus)
A non-technological, repeating, visible object in the sky, holding its position in the sky for hours
Given what happens in Endgame, why doesn't Dormammu come back to attack the universe?
Please, smoke with good manners
Is thermodynamics only applicable to systems in equilibrium?
Does a creature that is immune to a condition still make a saving throw?
Why does Bran Stark feel that Jon Snow "needs to know" about his lineage?
Is creating your own "experiment" considered cheating during a physics exam?
Colliding particles and Activation energy
How to return instance of struct, idiomatic way
How to define a function type which accepts any number of arguments in Go?How do I convert a go method to a func?Stack vs heap allocation of structs in Go, and how they relate to garbage collectionType converting slices of interfaces in GoWhat is an idiomatic way of representing enums in Go?Removing fields from struct or hiding them in JSON ResponsePointers vs. values in parameters and return valuesWrite struct to csv fileGolang: loop through fields of a struct modify them and and return the struct?Go function types that return structs being used with interfaces
.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty height:90px;width:728px;box-sizing:border-box;
I've got function that returns struct instance depending on argument it takes
func Factory(s string) interface
if s == 'SomeType'
return SomeType
else if s == 'AnotherType'
return AnotherType
this solution is good if I have a couple of structs to return but it's getting ugly if there are a lot of them, can I do it other way? Is there idiomatic way to do this?
go
add a comment |
I've got function that returns struct instance depending on argument it takes
func Factory(s string) interface
if s == 'SomeType'
return SomeType
else if s == 'AnotherType'
return AnotherType
this solution is good if I have a couple of structs to return but it's getting ugly if there are a lot of them, can I do it other way? Is there idiomatic way to do this?
go
1
You can use a map to map the string to what you want to return. Or if it's more complicated than returning an empty struct, the map can map the string to a function that produces the value.
– Andy Schweig
Mar 22 at 19:37
I didn’t down vote. It’s not uncommon for someone to just give guidance as opposed to giving a full solution.
– Andy Schweig
Mar 22 at 22:30
@AndySchweig I'm very sorry for that comment but sometimes I didn't understand why here people downvoting I can't find any logic in their behavior. I think mapping to function is what I'm searching for.
– latsha
Mar 23 at 13:54
add a comment |
I've got function that returns struct instance depending on argument it takes
func Factory(s string) interface
if s == 'SomeType'
return SomeType
else if s == 'AnotherType'
return AnotherType
this solution is good if I have a couple of structs to return but it's getting ugly if there are a lot of them, can I do it other way? Is there idiomatic way to do this?
go
I've got function that returns struct instance depending on argument it takes
func Factory(s string) interface
if s == 'SomeType'
return SomeType
else if s == 'AnotherType'
return AnotherType
this solution is good if I have a couple of structs to return but it's getting ugly if there are a lot of them, can I do it other way? Is there idiomatic way to do this?
go
go
edited Mar 22 at 21:56
Flimzy
41.1k1367102
41.1k1367102
asked Mar 22 at 19:13
latshalatsha
6551719
6551719
1
You can use a map to map the string to what you want to return. Or if it's more complicated than returning an empty struct, the map can map the string to a function that produces the value.
– Andy Schweig
Mar 22 at 19:37
I didn’t down vote. It’s not uncommon for someone to just give guidance as opposed to giving a full solution.
– Andy Schweig
Mar 22 at 22:30
@AndySchweig I'm very sorry for that comment but sometimes I didn't understand why here people downvoting I can't find any logic in their behavior. I think mapping to function is what I'm searching for.
– latsha
Mar 23 at 13:54
add a comment |
1
You can use a map to map the string to what you want to return. Or if it's more complicated than returning an empty struct, the map can map the string to a function that produces the value.
– Andy Schweig
Mar 22 at 19:37
I didn’t down vote. It’s not uncommon for someone to just give guidance as opposed to giving a full solution.
– Andy Schweig
Mar 22 at 22:30
@AndySchweig I'm very sorry for that comment but sometimes I didn't understand why here people downvoting I can't find any logic in their behavior. I think mapping to function is what I'm searching for.
– latsha
Mar 23 at 13:54
1
1
You can use a map to map the string to what you want to return. Or if it's more complicated than returning an empty struct, the map can map the string to a function that produces the value.
– Andy Schweig
Mar 22 at 19:37
You can use a map to map the string to what you want to return. Or if it's more complicated than returning an empty struct, the map can map the string to a function that produces the value.
– Andy Schweig
Mar 22 at 19:37
I didn’t down vote. It’s not uncommon for someone to just give guidance as opposed to giving a full solution.
– Andy Schweig
Mar 22 at 22:30
I didn’t down vote. It’s not uncommon for someone to just give guidance as opposed to giving a full solution.
– Andy Schweig
Mar 22 at 22:30
@AndySchweig I'm very sorry for that comment but sometimes I didn't understand why here people downvoting I can't find any logic in their behavior. I think mapping to function is what I'm searching for.
– latsha
Mar 23 at 13:54
@AndySchweig I'm very sorry for that comment but sometimes I didn't understand why here people downvoting I can't find any logic in their behavior. I think mapping to function is what I'm searching for.
– latsha
Mar 23 at 13:54
add a comment |
1 Answer
1
active
oldest
votes
As the comment said, you can use a map for your types. Looks like this. The factory function will return an instance if the type exists or nil if it doesn't.
package main
import (
"fmt"
"reflect"
)
type SomeType struct Something string
type AnotherType struct
type YetAnotherType struct
var typemap = map[string]interface
"SomeType": SomeType Something: "something" ,
"AnotherType": AnotherType,
"YetAnotherType": YetAnotherType,
func factory(s string) interface
t, ok := typemap[s]
if ok
return reflect.ValueOf(t)
return nil
func main()
fmt.Printf("%#vn", factory("SomeType"))
fmt.Printf("%#vn", factory("NoType"))
Playground link
Thanks for the answer @mad-wombat but isn't it returning the same instance every time I'm callingfactory
?
– latsha
Mar 22 at 19:56
Yes, it would. Sorry. You can use reflect to create a new value every time. Updated the code and link
– Mad Wombat
Mar 22 at 20:08
Actually, updated again, looks like using ValueOf() instead of New() provides a bit more flexibility. You can do initialization in your map and it will be preserved.
– Mad Wombat
Mar 22 at 20:12
looks promising will try it tomorrow.
– latsha
Mar 22 at 20:13
add a comment |
Your Answer
StackExchange.ifUsing("editor", function ()
StackExchange.using("externalEditor", function ()
StackExchange.using("snippets", function ()
StackExchange.snippets.init();
);
);
, "code-snippets");
StackExchange.ready(function()
var channelOptions =
tags: "".split(" "),
id: "1"
;
initTagRenderer("".split(" "), "".split(" "), channelOptions);
StackExchange.using("externalEditor", function()
// Have to fire editor after snippets, if snippets enabled
if (StackExchange.settings.snippets.snippetsEnabled)
StackExchange.using("snippets", function()
createEditor();
);
else
createEditor();
);
function createEditor()
StackExchange.prepareEditor(
heartbeatType: 'answer',
autoActivateHeartbeat: false,
convertImagesToLinks: true,
noModals: true,
showLowRepImageUploadWarning: true,
reputationToPostImages: 10,
bindNavPrevention: true,
postfix: "",
imageUploader:
brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
allowUrls: true
,
onDemand: true,
discardSelector: ".discard-answer"
,immediatelyShowMarkdownHelp:true
);
);
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function ()
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55306399%2fhow-to-return-instance-of-struct-idiomatic-way%23new-answer', 'question_page');
);
Post as a guest
Required, but never shown
1 Answer
1
active
oldest
votes
1 Answer
1
active
oldest
votes
active
oldest
votes
active
oldest
votes
As the comment said, you can use a map for your types. Looks like this. The factory function will return an instance if the type exists or nil if it doesn't.
package main
import (
"fmt"
"reflect"
)
type SomeType struct Something string
type AnotherType struct
type YetAnotherType struct
var typemap = map[string]interface
"SomeType": SomeType Something: "something" ,
"AnotherType": AnotherType,
"YetAnotherType": YetAnotherType,
func factory(s string) interface
t, ok := typemap[s]
if ok
return reflect.ValueOf(t)
return nil
func main()
fmt.Printf("%#vn", factory("SomeType"))
fmt.Printf("%#vn", factory("NoType"))
Playground link
Thanks for the answer @mad-wombat but isn't it returning the same instance every time I'm callingfactory
?
– latsha
Mar 22 at 19:56
Yes, it would. Sorry. You can use reflect to create a new value every time. Updated the code and link
– Mad Wombat
Mar 22 at 20:08
Actually, updated again, looks like using ValueOf() instead of New() provides a bit more flexibility. You can do initialization in your map and it will be preserved.
– Mad Wombat
Mar 22 at 20:12
looks promising will try it tomorrow.
– latsha
Mar 22 at 20:13
add a comment |
As the comment said, you can use a map for your types. Looks like this. The factory function will return an instance if the type exists or nil if it doesn't.
package main
import (
"fmt"
"reflect"
)
type SomeType struct Something string
type AnotherType struct
type YetAnotherType struct
var typemap = map[string]interface
"SomeType": SomeType Something: "something" ,
"AnotherType": AnotherType,
"YetAnotherType": YetAnotherType,
func factory(s string) interface
t, ok := typemap[s]
if ok
return reflect.ValueOf(t)
return nil
func main()
fmt.Printf("%#vn", factory("SomeType"))
fmt.Printf("%#vn", factory("NoType"))
Playground link
Thanks for the answer @mad-wombat but isn't it returning the same instance every time I'm callingfactory
?
– latsha
Mar 22 at 19:56
Yes, it would. Sorry. You can use reflect to create a new value every time. Updated the code and link
– Mad Wombat
Mar 22 at 20:08
Actually, updated again, looks like using ValueOf() instead of New() provides a bit more flexibility. You can do initialization in your map and it will be preserved.
– Mad Wombat
Mar 22 at 20:12
looks promising will try it tomorrow.
– latsha
Mar 22 at 20:13
add a comment |
As the comment said, you can use a map for your types. Looks like this. The factory function will return an instance if the type exists or nil if it doesn't.
package main
import (
"fmt"
"reflect"
)
type SomeType struct Something string
type AnotherType struct
type YetAnotherType struct
var typemap = map[string]interface
"SomeType": SomeType Something: "something" ,
"AnotherType": AnotherType,
"YetAnotherType": YetAnotherType,
func factory(s string) interface
t, ok := typemap[s]
if ok
return reflect.ValueOf(t)
return nil
func main()
fmt.Printf("%#vn", factory("SomeType"))
fmt.Printf("%#vn", factory("NoType"))
Playground link
As the comment said, you can use a map for your types. Looks like this. The factory function will return an instance if the type exists or nil if it doesn't.
package main
import (
"fmt"
"reflect"
)
type SomeType struct Something string
type AnotherType struct
type YetAnotherType struct
var typemap = map[string]interface
"SomeType": SomeType Something: "something" ,
"AnotherType": AnotherType,
"YetAnotherType": YetAnotherType,
func factory(s string) interface
t, ok := typemap[s]
if ok
return reflect.ValueOf(t)
return nil
func main()
fmt.Printf("%#vn", factory("SomeType"))
fmt.Printf("%#vn", factory("NoType"))
Playground link
edited Mar 22 at 20:08
answered Mar 22 at 19:49
Mad WombatMad Wombat
6,98244071
6,98244071
Thanks for the answer @mad-wombat but isn't it returning the same instance every time I'm callingfactory
?
– latsha
Mar 22 at 19:56
Yes, it would. Sorry. You can use reflect to create a new value every time. Updated the code and link
– Mad Wombat
Mar 22 at 20:08
Actually, updated again, looks like using ValueOf() instead of New() provides a bit more flexibility. You can do initialization in your map and it will be preserved.
– Mad Wombat
Mar 22 at 20:12
looks promising will try it tomorrow.
– latsha
Mar 22 at 20:13
add a comment |
Thanks for the answer @mad-wombat but isn't it returning the same instance every time I'm callingfactory
?
– latsha
Mar 22 at 19:56
Yes, it would. Sorry. You can use reflect to create a new value every time. Updated the code and link
– Mad Wombat
Mar 22 at 20:08
Actually, updated again, looks like using ValueOf() instead of New() provides a bit more flexibility. You can do initialization in your map and it will be preserved.
– Mad Wombat
Mar 22 at 20:12
looks promising will try it tomorrow.
– latsha
Mar 22 at 20:13
Thanks for the answer @mad-wombat but isn't it returning the same instance every time I'm calling
factory
?– latsha
Mar 22 at 19:56
Thanks for the answer @mad-wombat but isn't it returning the same instance every time I'm calling
factory
?– latsha
Mar 22 at 19:56
Yes, it would. Sorry. You can use reflect to create a new value every time. Updated the code and link
– Mad Wombat
Mar 22 at 20:08
Yes, it would. Sorry. You can use reflect to create a new value every time. Updated the code and link
– Mad Wombat
Mar 22 at 20:08
Actually, updated again, looks like using ValueOf() instead of New() provides a bit more flexibility. You can do initialization in your map and it will be preserved.
– Mad Wombat
Mar 22 at 20:12
Actually, updated again, looks like using ValueOf() instead of New() provides a bit more flexibility. You can do initialization in your map and it will be preserved.
– Mad Wombat
Mar 22 at 20:12
looks promising will try it tomorrow.
– latsha
Mar 22 at 20:13
looks promising will try it tomorrow.
– latsha
Mar 22 at 20:13
add a comment |
Thanks for contributing an answer to Stack Overflow!
- Please be sure to answer the question. Provide details and share your research!
But avoid …
- Asking for help, clarification, or responding to other answers.
- Making statements based on opinion; back them up with references or personal experience.
To learn more, see our tips on writing great answers.
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function ()
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55306399%2fhow-to-return-instance-of-struct-idiomatic-way%23new-answer', 'question_page');
);
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
i,Z3h8emm,LkqYMo,bIZBQ2 xB9AmSp,mrxDpDE75Au 7Ac8l,DDr,TAX
1
You can use a map to map the string to what you want to return. Or if it's more complicated than returning an empty struct, the map can map the string to a function that produces the value.
– Andy Schweig
Mar 22 at 19:37
I didn’t down vote. It’s not uncommon for someone to just give guidance as opposed to giving a full solution.
– Andy Schweig
Mar 22 at 22:30
@AndySchweig I'm very sorry for that comment but sometimes I didn't understand why here people downvoting I can't find any logic in their behavior. I think mapping to function is what I'm searching for.
– latsha
Mar 23 at 13:54