Difference in a function implementation when instantiating an object with different function signaturesPointers vs. values in parameters and return valuesGolang Pointer and Struct member functionStack vs heap allocation of structs in Go, and how they relate to garbage collectionWhy does the compiler require such a strict match for function signatures?When is the init() function run?Why does putting a pointer in an interface in Go cause reflect to lose the name of the type?Implicit interface conversion in golangReturn different specialised implementations of interfaces from the same function in Go langfunction type parameter match in golangGolang change type of pointer interfaceStrange behaviour when Unmarshalling into struct in GoCall function of specific type in Go

How to draw the figure with four pentagons?

Could gravitational lensing be used to protect a spaceship from a laser?

Why does Arabsat 6A need a Falcon Heavy to launch

prove that the matrix A is diagonalizable

Can a rocket refuel on Mars from water?

Neighboring nodes in the network

Doing something right before you need it - expression for this?

Is delete *p an alternative to delete [] p?

Blender 2.8 I can't see vertices, edges or faces in edit mode

I would say: "You are another teacher", but she is a woman and I am a man

How to model explosives?

Do I have a twin with permutated remainders?

If a Gelatinous Cube takes up the entire space of a Pit Trap, what happens when a creature falls into the trap but succeeds on the saving throw?

How to prevent "they're falling in love" trope

Fully-Firstable Anagram Sets

Arrow those variables!

In a Spin are Both Wings Stalled?

Emailing HOD to enhance faculty application

Is Lorentz symmetry broken if SUSY is broken?

Where does SFDX store details about scratch orgs?

What is the PIE reconstruction for word-initial alpha with rough breathing?

Why do I get two different answers for this counting problem?

Combinations of multiple lists

How much of data wrangling is a data scientist's job?



Difference in a function implementation when instantiating an object with different function signatures


Pointers vs. values in parameters and return valuesGolang Pointer and Struct member functionStack vs heap allocation of structs in Go, and how they relate to garbage collectionWhy does the compiler require such a strict match for function signatures?When is the init() function run?Why does putting a pointer in an interface in Go cause reflect to lose the name of the type?Implicit interface conversion in golangReturn different specialised implementations of interfaces from the same function in Go langfunction type parameter match in golangGolang change type of pointer interfaceStrange behaviour when Unmarshalling into struct in GoCall function of specific type in Go






.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty height:90px;width:728px;box-sizing:border-box;








0















Came across the following differences a function implementations. What is the reasoning behind Example 1 returning a pointer and Example 2 returning an actual object?



type MyInterface interface 
Func (param int) float64 //just random signature


//MyInterfaceImpl implements MyInterface
type MyInterfaceImpl struct


//actual implementation
func (myObj *MyInterfaceImpl) Func(param int) float64
return float64(param)



Example 1: the pointer to the MyInterfaceImpl is returned when function returns an interface



func NewMyInterface() MyInterface 
return &MyInterfaceImpl



Example 2: actual object of MyInterfaceImpl is returned when function returns the object



func NewMyInterfaceImpl() MyInterfaceImpl 
return MyInterfaceImpl



UPDATE: This piece of code compiles and runs



func main() 
myIf := NewMyInterface()
fmt.Printf("Hi from inteface %fn", myIf.Func(1000))

myImpl := NewMyInterfaceImpl()
fmt.Printf("Hi from impl %fn", myImpl.Func(100))



UPDATE2: Question clarification.



This sounds weird (for me) to have a declaration of func NewMyInterface() MyInterface and a valid implementation of return &MyInterfaceImpl where a pointer is returned. I would expect to return an object of MyInterfaceImpl with return MyInterfaceImpl



If the language allows such types of constructs, there must be a reason for that. Eventually, I am looking for a following answer: "The function declaration returns an interface. Because the interface has a property X it is does not make sense to return an object, but the only valid option is a pointer".










share|improve this question
























  • Are you sure its not NewMyInterface() *MyInterface { for the first example?

    – Ibu
    Mar 8 at 22:02











  • @lbu Updated the description

    – Timofey
    Mar 8 at 22:13












  • Possible duplicate of Golang Pointer and Struct member function

    – munk
    Mar 8 at 22:21






  • 1





    What is the reasoning behind Example 1 returning a pointer and Example 2 returning an actual object? depends what they do, their members, how they are being used. With current examples its hard to tell. Now, as a rule of thumb, take interface, return structs. to read medium.com/@cep21/…

    – mh-cbon
    Mar 8 at 22:49






  • 1





    @mh-cbon Example 1 has to return a pointer, as MyInterfaceImpl doesn't implement MyInterface (despite the name...) But I agree it's hard to tell what the question is.

    – ᆼᆺᆼ
    Mar 8 at 22:55


















0















Came across the following differences a function implementations. What is the reasoning behind Example 1 returning a pointer and Example 2 returning an actual object?



type MyInterface interface 
Func (param int) float64 //just random signature


//MyInterfaceImpl implements MyInterface
type MyInterfaceImpl struct


//actual implementation
func (myObj *MyInterfaceImpl) Func(param int) float64
return float64(param)



Example 1: the pointer to the MyInterfaceImpl is returned when function returns an interface



func NewMyInterface() MyInterface 
return &MyInterfaceImpl



Example 2: actual object of MyInterfaceImpl is returned when function returns the object



func NewMyInterfaceImpl() MyInterfaceImpl 
return MyInterfaceImpl



UPDATE: This piece of code compiles and runs



func main() 
myIf := NewMyInterface()
fmt.Printf("Hi from inteface %fn", myIf.Func(1000))

myImpl := NewMyInterfaceImpl()
fmt.Printf("Hi from impl %fn", myImpl.Func(100))



UPDATE2: Question clarification.



This sounds weird (for me) to have a declaration of func NewMyInterface() MyInterface and a valid implementation of return &MyInterfaceImpl where a pointer is returned. I would expect to return an object of MyInterfaceImpl with return MyInterfaceImpl



If the language allows such types of constructs, there must be a reason for that. Eventually, I am looking for a following answer: "The function declaration returns an interface. Because the interface has a property X it is does not make sense to return an object, but the only valid option is a pointer".










share|improve this question
























  • Are you sure its not NewMyInterface() *MyInterface { for the first example?

    – Ibu
    Mar 8 at 22:02











  • @lbu Updated the description

    – Timofey
    Mar 8 at 22:13












  • Possible duplicate of Golang Pointer and Struct member function

    – munk
    Mar 8 at 22:21






  • 1





    What is the reasoning behind Example 1 returning a pointer and Example 2 returning an actual object? depends what they do, their members, how they are being used. With current examples its hard to tell. Now, as a rule of thumb, take interface, return structs. to read medium.com/@cep21/…

    – mh-cbon
    Mar 8 at 22:49






  • 1





    @mh-cbon Example 1 has to return a pointer, as MyInterfaceImpl doesn't implement MyInterface (despite the name...) But I agree it's hard to tell what the question is.

    – ᆼᆺᆼ
    Mar 8 at 22:55














0












0








0


0






Came across the following differences a function implementations. What is the reasoning behind Example 1 returning a pointer and Example 2 returning an actual object?



type MyInterface interface 
Func (param int) float64 //just random signature


//MyInterfaceImpl implements MyInterface
type MyInterfaceImpl struct


//actual implementation
func (myObj *MyInterfaceImpl) Func(param int) float64
return float64(param)



Example 1: the pointer to the MyInterfaceImpl is returned when function returns an interface



func NewMyInterface() MyInterface 
return &MyInterfaceImpl



Example 2: actual object of MyInterfaceImpl is returned when function returns the object



func NewMyInterfaceImpl() MyInterfaceImpl 
return MyInterfaceImpl



UPDATE: This piece of code compiles and runs



func main() 
myIf := NewMyInterface()
fmt.Printf("Hi from inteface %fn", myIf.Func(1000))

myImpl := NewMyInterfaceImpl()
fmt.Printf("Hi from impl %fn", myImpl.Func(100))



UPDATE2: Question clarification.



This sounds weird (for me) to have a declaration of func NewMyInterface() MyInterface and a valid implementation of return &MyInterfaceImpl where a pointer is returned. I would expect to return an object of MyInterfaceImpl with return MyInterfaceImpl



If the language allows such types of constructs, there must be a reason for that. Eventually, I am looking for a following answer: "The function declaration returns an interface. Because the interface has a property X it is does not make sense to return an object, but the only valid option is a pointer".










share|improve this question
















Came across the following differences a function implementations. What is the reasoning behind Example 1 returning a pointer and Example 2 returning an actual object?



type MyInterface interface 
Func (param int) float64 //just random signature


//MyInterfaceImpl implements MyInterface
type MyInterfaceImpl struct


//actual implementation
func (myObj *MyInterfaceImpl) Func(param int) float64
return float64(param)



Example 1: the pointer to the MyInterfaceImpl is returned when function returns an interface



func NewMyInterface() MyInterface 
return &MyInterfaceImpl



Example 2: actual object of MyInterfaceImpl is returned when function returns the object



func NewMyInterfaceImpl() MyInterfaceImpl 
return MyInterfaceImpl



UPDATE: This piece of code compiles and runs



func main() 
myIf := NewMyInterface()
fmt.Printf("Hi from inteface %fn", myIf.Func(1000))

myImpl := NewMyInterfaceImpl()
fmt.Printf("Hi from impl %fn", myImpl.Func(100))



UPDATE2: Question clarification.



This sounds weird (for me) to have a declaration of func NewMyInterface() MyInterface and a valid implementation of return &MyInterfaceImpl where a pointer is returned. I would expect to return an object of MyInterfaceImpl with return MyInterfaceImpl



If the language allows such types of constructs, there must be a reason for that. Eventually, I am looking for a following answer: "The function declaration returns an interface. Because the interface has a property X it is does not make sense to return an object, but the only valid option is a pointer".







go






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Mar 8 at 23:10







Timofey

















asked Mar 8 at 21:38









TimofeyTimofey

1,61923143




1,61923143












  • Are you sure its not NewMyInterface() *MyInterface { for the first example?

    – Ibu
    Mar 8 at 22:02











  • @lbu Updated the description

    – Timofey
    Mar 8 at 22:13












  • Possible duplicate of Golang Pointer and Struct member function

    – munk
    Mar 8 at 22:21






  • 1





    What is the reasoning behind Example 1 returning a pointer and Example 2 returning an actual object? depends what they do, their members, how they are being used. With current examples its hard to tell. Now, as a rule of thumb, take interface, return structs. to read medium.com/@cep21/…

    – mh-cbon
    Mar 8 at 22:49






  • 1





    @mh-cbon Example 1 has to return a pointer, as MyInterfaceImpl doesn't implement MyInterface (despite the name...) But I agree it's hard to tell what the question is.

    – ᆼᆺᆼ
    Mar 8 at 22:55


















  • Are you sure its not NewMyInterface() *MyInterface { for the first example?

    – Ibu
    Mar 8 at 22:02











  • @lbu Updated the description

    – Timofey
    Mar 8 at 22:13












  • Possible duplicate of Golang Pointer and Struct member function

    – munk
    Mar 8 at 22:21






  • 1





    What is the reasoning behind Example 1 returning a pointer and Example 2 returning an actual object? depends what they do, their members, how they are being used. With current examples its hard to tell. Now, as a rule of thumb, take interface, return structs. to read medium.com/@cep21/…

    – mh-cbon
    Mar 8 at 22:49






  • 1





    @mh-cbon Example 1 has to return a pointer, as MyInterfaceImpl doesn't implement MyInterface (despite the name...) But I agree it's hard to tell what the question is.

    – ᆼᆺᆼ
    Mar 8 at 22:55

















Are you sure its not NewMyInterface() *MyInterface { for the first example?

– Ibu
Mar 8 at 22:02





Are you sure its not NewMyInterface() *MyInterface { for the first example?

– Ibu
Mar 8 at 22:02













@lbu Updated the description

– Timofey
Mar 8 at 22:13






@lbu Updated the description

– Timofey
Mar 8 at 22:13














Possible duplicate of Golang Pointer and Struct member function

– munk
Mar 8 at 22:21





Possible duplicate of Golang Pointer and Struct member function

– munk
Mar 8 at 22:21




1




1





What is the reasoning behind Example 1 returning a pointer and Example 2 returning an actual object? depends what they do, their members, how they are being used. With current examples its hard to tell. Now, as a rule of thumb, take interface, return structs. to read medium.com/@cep21/…

– mh-cbon
Mar 8 at 22:49





What is the reasoning behind Example 1 returning a pointer and Example 2 returning an actual object? depends what they do, their members, how they are being used. With current examples its hard to tell. Now, as a rule of thumb, take interface, return structs. to read medium.com/@cep21/…

– mh-cbon
Mar 8 at 22:49




1




1





@mh-cbon Example 1 has to return a pointer, as MyInterfaceImpl doesn't implement MyInterface (despite the name...) But I agree it's hard to tell what the question is.

– ᆼᆺᆼ
Mar 8 at 22:55






@mh-cbon Example 1 has to return a pointer, as MyInterfaceImpl doesn't implement MyInterface (despite the name...) But I agree it's hard to tell what the question is.

– ᆼᆺᆼ
Mar 8 at 22:55













1 Answer
1






active

oldest

votes


















1














Even though I'm not sure which part of the code the question is about, let me explain what the code does:



MyInterface is implemented by anything having a Func(int)float64 method.
*MyInterfaceImpl has such a method. However, MyInterfaceImpl does not (the method has a pointer receiver).



NewMyInterface() thus has to return a pointer. MyInterfaceImpl wouldn't implement MyInterface.



Does this answer your question?




Another question might be why the call myImpl.Func(100) works, despite the above. This is because Go automatically takes the address of the receiver when calling its methods with pointer receivers.

This is explained in more detail for example here.






share|improve this answer

























  • Could you please clarify why MyInterfaceImpl does not implement MyInterface? It sounds like I am missing a fundamental go knowledge here.

    – Timofey
    Mar 8 at 23:17






  • 1





    The spec explains it. The method set for a value type does not include pointer receiver methods.

    – Cerise Limón
    Mar 8 at 23:18











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%2f55071358%2fdifference-in-a-function-implementation-when-instantiating-an-object-with-differ%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














Even though I'm not sure which part of the code the question is about, let me explain what the code does:



MyInterface is implemented by anything having a Func(int)float64 method.
*MyInterfaceImpl has such a method. However, MyInterfaceImpl does not (the method has a pointer receiver).



NewMyInterface() thus has to return a pointer. MyInterfaceImpl wouldn't implement MyInterface.



Does this answer your question?




Another question might be why the call myImpl.Func(100) works, despite the above. This is because Go automatically takes the address of the receiver when calling its methods with pointer receivers.

This is explained in more detail for example here.






share|improve this answer

























  • Could you please clarify why MyInterfaceImpl does not implement MyInterface? It sounds like I am missing a fundamental go knowledge here.

    – Timofey
    Mar 8 at 23:17






  • 1





    The spec explains it. The method set for a value type does not include pointer receiver methods.

    – Cerise Limón
    Mar 8 at 23:18















1














Even though I'm not sure which part of the code the question is about, let me explain what the code does:



MyInterface is implemented by anything having a Func(int)float64 method.
*MyInterfaceImpl has such a method. However, MyInterfaceImpl does not (the method has a pointer receiver).



NewMyInterface() thus has to return a pointer. MyInterfaceImpl wouldn't implement MyInterface.



Does this answer your question?




Another question might be why the call myImpl.Func(100) works, despite the above. This is because Go automatically takes the address of the receiver when calling its methods with pointer receivers.

This is explained in more detail for example here.






share|improve this answer

























  • Could you please clarify why MyInterfaceImpl does not implement MyInterface? It sounds like I am missing a fundamental go knowledge here.

    – Timofey
    Mar 8 at 23:17






  • 1





    The spec explains it. The method set for a value type does not include pointer receiver methods.

    – Cerise Limón
    Mar 8 at 23:18













1












1








1







Even though I'm not sure which part of the code the question is about, let me explain what the code does:



MyInterface is implemented by anything having a Func(int)float64 method.
*MyInterfaceImpl has such a method. However, MyInterfaceImpl does not (the method has a pointer receiver).



NewMyInterface() thus has to return a pointer. MyInterfaceImpl wouldn't implement MyInterface.



Does this answer your question?




Another question might be why the call myImpl.Func(100) works, despite the above. This is because Go automatically takes the address of the receiver when calling its methods with pointer receivers.

This is explained in more detail for example here.






share|improve this answer















Even though I'm not sure which part of the code the question is about, let me explain what the code does:



MyInterface is implemented by anything having a Func(int)float64 method.
*MyInterfaceImpl has such a method. However, MyInterfaceImpl does not (the method has a pointer receiver).



NewMyInterface() thus has to return a pointer. MyInterfaceImpl wouldn't implement MyInterface.



Does this answer your question?




Another question might be why the call myImpl.Func(100) works, despite the above. This is because Go automatically takes the address of the receiver when calling its methods with pointer receivers.

This is explained in more detail for example here.







share|improve this answer














share|improve this answer



share|improve this answer








edited Mar 8 at 23:31

























answered Mar 8 at 23:09









ᆼᆺᆼᆼᆺᆼ

8,67943563




8,67943563












  • Could you please clarify why MyInterfaceImpl does not implement MyInterface? It sounds like I am missing a fundamental go knowledge here.

    – Timofey
    Mar 8 at 23:17






  • 1





    The spec explains it. The method set for a value type does not include pointer receiver methods.

    – Cerise Limón
    Mar 8 at 23:18

















  • Could you please clarify why MyInterfaceImpl does not implement MyInterface? It sounds like I am missing a fundamental go knowledge here.

    – Timofey
    Mar 8 at 23:17






  • 1





    The spec explains it. The method set for a value type does not include pointer receiver methods.

    – Cerise Limón
    Mar 8 at 23:18
















Could you please clarify why MyInterfaceImpl does not implement MyInterface? It sounds like I am missing a fundamental go knowledge here.

– Timofey
Mar 8 at 23:17





Could you please clarify why MyInterfaceImpl does not implement MyInterface? It sounds like I am missing a fundamental go knowledge here.

– Timofey
Mar 8 at 23:17




1




1





The spec explains it. The method set for a value type does not include pointer receiver methods.

– Cerise Limón
Mar 8 at 23:18





The spec explains it. The method set for a value type does not include pointer receiver methods.

– Cerise Limón
Mar 8 at 23:18



















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%2f55071358%2fdifference-in-a-function-implementation-when-instantiating-an-object-with-differ%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

Thal And Out Agency railway station See also References External links Navigation menuOfficial Web Site of Pakistan RailwaysArchivedOfficial Web Site of Pakistan Railwayseeexpanding ite

Understanding generators in Python2019 Community Moderator ElectionGenerator function not working pythonFor loop not executing two timesGenerators - Printing generated valuesWhy can a python generator only be used once?What exactly do generators do?What does the “yield” keyword do?What does “list comprehension” mean? How does it work and how can I use it?sklearn Kfold acces single fold instead of for loopIs a generator the callable? Which is the generator?Apply Border To Range Of Cells Using OpenpyxlCalling an external command in PythonWhat are metaclasses in Python?What is the difference between @staticmethod and @classmethod?Finding the index of an item given a list containing it in PythonDifference between append vs. extend list methods in PythonHow can I safely create a nested directory in Python?Does Python have a ternary conditional operator?Understanding slice notationUnderstanding Python super() with __init__() methodsDoes Python have a string 'contains' substring method?

How can I change the color of pagination dots of UIPageControl?How to change UIPageControl dotsIs there a way to change page indicator dots colorCustomize dot with image of UIPageControl at index 0 of UIPageControlNo visible @interface for 'NSObject<PageControlDelegate>' declares the selector 'pageControlPageDidChange:'How to change the color of pagination dots in UIPageControl with a different color per pagepagecontrol indicator custom image instead of DefaultChanging the colour of UIPageControl dots in MonoTouchpagecontrol selectable page visibility color?Alternative way to load ViewControllers on a UIPageControlHow to set only layer.border-color for UIpage control dots in swiftHow can I develop for iPhone using a Windows development machine?How to change the name of an iOS app?UITableView - change section header coloruipagecontrol indicator(dot)issueCustom UIPageControl dots color not changingchange the interspace between UIPageControl dotsHow to change Status Bar text color in iOSHow can I change image tintColor in iOS and WatchKitUIPageControl dots with larger space in between each dotsHow to change the color of pagination dots in UIPageControl with a different color per page