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

How to preserve electronics (computers, tablets and phones) for hundreds of years Announcing the arrival of Valued Associate #679: Cesar Manara Planned maintenance scheduled April 23, 2019 at 23:30 UTC (7:30pm US/Eastern) The network's official Twitter account is up and running again. What content…How might modern humans leave a message for 50,000 years?How would an aquatic race develop computers?How do we make computers care for human life?Keeping supplies for 1000 yearsWhat will cell phones become in 100 years?What body armor protects against a laser?Could a society attain 1800s technology if limited to using copper and bronze?Electricity power (magic) and electronicsScavenging metal resources in post-apocalypse after 100 yearsWhy would precursors create devices that can survive and still work after hundreds of years?

155 수학 과학 기타 둘러보기 메뉴eh추가해eh문서를 완성해

Convert JSON to MapSimplest way to convert a string representing JSON array into Java array List of key value pairsHow to take String JSON values into HashMapConvert a JSON String to a HashMapCreating BSON object from JSON stringJSONObject - How to get a value ?Better Map ConstructorReading JSON from Url javaUpdate columns if input values are not null otherwise ignore and keep the existing values of column in databaseHow to store object represented as Json string into Couchbase Lite?Go JSON into MapHow do I efficiently iterate over each entry in a Java Map?Sort a Map<Key, Value> by valuesHow to round a number to n decimal places in JavaCan comments be used in JSON?How do I read / convert an InputStream into a String in Java?How can I pretty-print JSON in a shell script?What is the correct JSON content type?How can I deserialize JSON to a simple Dictionary<string,string> in ASP.NET?Why does Google prepend while(1); to their JSON responses?Parse JSON in JavaScript?