简体   繁体   中英

map a struct to a function in go

import (
    "net/url"
)

type Route struct{
    filepath string
    url url.URL
}

func hello(){
    fmt.Println("Hello World")
}

func main() {

    routes := map[Route]func{
        Route{url.Parse("/home"), "/var/www/index.html"} : hello
    }

}

I cannot figure out what syntax error is preventing me from mapping a Route struct to a function.

I am getting this error:

./main.go:24:26: syntax error: unexpected {, expecting (

./main.go:25:8: syntax error: unexpected {, expecting comma or )

  1. type is not func but func()
  2. you need to take care of url.Parse 's error

There is a refactored code:

package main

import (
    "fmt"
    "net/url"
)

type Route struct {
    filepath string
    url      *url.URL
}

func hello() {
    fmt.Println("Hello World")
}

func mustParse(rawURL string) *url.URL {
    parsedURL, err := url.Parse(rawURL)
    if err != nil {
        panic(err)
    }
    return parsedURL
}

func main() {

    routes := map[Route]func(){

        Route{"/var/www/index.html", mustParse("/home")}: hello,
    }

    fmt.Printf("routes: %+v\n", routes)

}

The solution with panic might not be the best if you don't know the input dispositions.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM