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

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;








0















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?










share|improve this question



















  • 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

















0















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?










share|improve this question



















  • 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













0












0








0








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?










share|improve this question
















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






share|improve this question















share|improve this question













share|improve this question




share|improve this question








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












  • 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












1 Answer
1






active

oldest

votes


















1














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






share|improve this answer

























  • 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











  • 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











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
);



);













draft saved

draft discarded


















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









1














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






share|improve this answer

























  • 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











  • 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















1














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






share|improve this answer

























  • 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











  • 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













1












1








1







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






share|improve this answer















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







share|improve this answer














share|improve this answer



share|improve this answer








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 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











  • 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











  • 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



















draft saved

draft discarded
















































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.




draft saved


draft discarded














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





















































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







Popular posts from this blog

Kamusi Yaliyomo Aina za kamusi | Muundo wa kamusi | Faida za kamusi | Dhima ya picha katika kamusi | Marejeo | Tazama pia | Viungo vya nje | UrambazajiKuhusu kamusiGo-SwahiliWiki-KamusiKamusi ya Kiswahili na Kiingerezakuihariri na kuongeza habari

Swift 4 - func physicsWorld not invoked on collision? The Next CEO of Stack OverflowHow to call Objective-C code from Swift#ifdef replacement in the Swift language@selector() in Swift?#pragma mark in Swift?Swift for loop: for index, element in array?dispatch_after - GCD in Swift?Swift Beta performance: sorting arraysSplit a String into an array in Swift?The use of Swift 3 @objc inference in Swift 4 mode is deprecated?How to optimize UITableViewCell, because my UITableView lags

Access current req object everywhere in Node.js ExpressWhy are global variables considered bad practice? (node.js)Using req & res across functionsHow do I get the path to the current script with Node.js?What is Node.js' Connect, Express and “middleware”?Node.js w/ express error handling in callbackHow to access the GET parameters after “?” in Express?Modify Node.js req object parametersAccess “app” variable inside of ExpressJS/ConnectJS middleware?Node.js Express app - request objectAngular Http Module considered middleware?Session variables in ExpressJSAdd properties to the req object in expressjs with Typescript