Skip to content

template: could evalArg/validateType propagate a value of type T to *T, if a method/fn's argument is of type *T? #2235

@gopherbot

Description

@gopherbot

by mt4swm:

Sometimes one has a struct that contains other structs, or
slices of structs, as members:

    type T2 struct {
        A T1
        B []T1
    } 

When using the template engine with this struct as data, I
would like to be able to call a Method or a template function
that has an argument of type *T1, not T1, for efficiency.

For now, if a template contains
    {{ func .A }}

with func being a user defined function taking one argument
of type *T1, the template engine will print an error like:

    template: wrong type for value; expected *T1; got T1

I think it would be nice if the template engine could
automatically take the address of a value, if it detects that
its type then would match a function argument's type.

The patch below to exec.c:validateType tries to implement
this behaviour. It appears to work both in case of methods and functions.

Michael

--- a/src/pkg/template/exec.go
+++ b/src/pkg/template/exec.go
@@ -506,7 +506,11 @@
        s.errorf("invalid value; expected %s", typ)
    }
    if !value.Type().AssignableTo(typ) {
-       s.errorf("wrong type for value; expected %s; got %s", typ, value.Type())
+       if reflect.PtrTo(value.Type()).AssignableTo(typ) {
+           value = value.Addr()
+       } else {
+           s.errorf("wrong type for value; expected %s; got %s", typ, value.Type())
+       }
    }
    return value
 }

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions