Skip to content

proposal: text/template: Template.Scan #66707

@3052

Description

@3052

Proposal Details

currently you can implement fmt.Fprintf like this:

package main

import (
   "io"
   "os"
   "text/template"
)

func fprintf(w io.Writer, format string, a any) error {
   text, err := new(template.Template).Parse(format)
   if err != nil {
      return err
   }
   return text.Execute(w, a)
}

func main() {
   var a struct {
      Hello string
      World string
   }
   a.Hello = "hello"
   a.World = "world"
   fprintf(os.Stdout, "http://example.com/{{.Hello}}/{{.World}}", a)
}

but you cannot do the opposite. ideally some method like this would exist:

func (t *Template) Scan(rd io.Reader, data any) error

then you could implement fmt.Fscanf:

package main

import (
   "io"
   "os"
   "text/template"
)

func fscanf(r io.Reader, format string, a any) error {
   text, err := new(template.Template).Parse(format)
   if err != nil {
      return err
   }
   return text.Scan(r, a)
}

func main() {
   r := strings.NewReader("http://example.com/hello/world")
   var a struct {
      Hello string
      World string
   }
   fscanf(r, "http://example.com/{{.Hello}}/{{.World}}", &a)
}

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions