Trying to return a value (no pointer) to a generic type?

I have the following function which works:

package main

type CISettings interface {
	Clone() CISettings
	Merge(other CISettings)
}

type Settings struct{}

func (s *Settings) Clone() CISettings {
	return &Settings{}
}

func (s *Settings) Merge(other CISettings) {
}

func ParseCISettings[T CISettings](settings T) error {
	sett := settings.Clone()
	settings.Merge(sett)
	return nil
}

func main() {
	sett := Settings{}
	ParseCISettings[*Settings](&sett)
}

link

I have trouble finding out why a signature where I return the settings does not work:

ParseCISettings[T CISettings](settings T, err error)

link

I am not grocking what the compiler trys to tell me. If I make value receivers it works, but thats not how Merge should be implemented, it needs a pointer receiver.

This is a very simple interface problem, in your code implementation, it is ‘*Settings’ that implements ‘CISettings’, not ‘Settings’.

You can try calling it like this:

func main() {
	sett := Settings{}
	ParseCISettings(&sett)
}

You understood the question wrong:
I want to return a new type Settings not passing it in.

I don’t know what you’re trying to express, if you can, write some pseudocode.

I am still a little bit confused of you expected results, but maybe you are trying to do something like this:

?

It tells you that you cannot use Settings type as the interface, because this type does not implement this interface. The error is in main function here:

ParseCISettings[Settings]()

You implemented both methods Clone and Merge for pointer: *Settings!

func (s *Settings) Clone() CISettings {
	return &Settings{}
}

func (s *Settings) Merge(other CISettings) {}

You either need to change it to value itself or change the generic type you are passing in main:

ParseCISettings[*Settings]()

Thanks, thats close to what I want.
But what ever the parse function does I wanted to return a value Settings (or a pointer to it). But I dont know how to construct such a thing, cause var v T does not work. Or how do I construct a new value in a generic function using T as parameter?

Can you please be more specific on what exactly you are trying to achieve? What parameters the parsing function should have, what it will return, because now, I’m lost

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.