Handling methods with a pointer receiver

I have an interface like,

type cacheControlDirectives interface {
  setDirective(key string, value string) error
}

And two structs implement it like,

type requestCacheControlDirectives struct {
    //...
}
func (rqcd *requestCacheControlDirectives) setDirective(key string, value string) error {
    //...
}

type responseCacheControlDirectives struct {
    //...
}
func (rqcd *responseCacheControlDirectives) setDirective(key string, value string) error {
    //...
}

I have a function to parse the input string and assign the values to the respective structs.

func parseCacheControl(value string, ccd cacheControlDirectives) (cacheControlDirectives, []error) {
	var err []error
	directives := strings.Split(value, ",")
	for _, directive := range directives {
		directive := strings.TrimSpace(directive)
		s := strings.Split(directive, "=")
		if len(s) == 1 {
			e := ccd.setDirective(s[0], "true")
			if e != nil {
				err = append(err, e)
			}
		} else if len(s) == 2 {
			ccd.setDirective(s[0], s[1])
		}
	}
	return ccd, err
}

Now when I try to use this function like this,

rqcd, e := parseCacheControl(req.Header.Get("Cache-Control"), &requestCacheControlDirectives{})
if e != nil {
	err = append(err, e...)
}
var rd requestCacheControlDirectives
rd = rqcd

It’s showing cannot use rqcd (type cacheControlDirectives) as type requestCacheControlDirectives in assignment error. How to solve this?

Your function is returning an interface, but you want the concrete type. You use a type assertion to extract it. But usually, if a function returns an interface you should probably continue using that interface. Also, it looks like you’re just returning the interface you got as a parameter which is probably unnecessary?

1 Like

Why returning the interface you got as a parameter which is unnecessary? I cannot take a pointer of the interface type. What other options do I have?

You have several different things happening in this code which is not idiomatic. This is causing some of the mechanical issues you are having between working with concrete struct type values and your interface values. Start with these posts.

http://www.goinggo.net/2014/05/methods-interfaces-and-embedded-types.html
http://www.goinggo.net/2015/03/object-oriented-programming-mechanics.html
http://www.goinggo.net/2015/09/composition-with-go.html

Also, try to reduce the length of your identifiers.

2 Likes

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