在Go语言的for循环中将值转换为字符串

huangapple go评论86阅读模式
英文:

Converting Value To String In For Loop In GoLang

问题

在Go语言中,我正在通过以下方式循环遍历我的表单数据:

for key, values := range r.Form {   // 遍历map
    for _, value := range values {    // 遍历[]string
        fmt.Println(key, value)
    }
}

我可以像这样将数据打印到终端,但我需要将这些数据存储为字符串,以便在for循环之外访问它。当循环结束后,我该如何将其放入一个变量中,以便在循环之外调用?

我的目标是通过连接这三个字符串来构建一个URL:

var SearchUrl = "https://api.themoviedb.org/3/search/movie?query="
var MovieSearch []string = r.Form["GetSearchKey"]
var apiKey = "&api_key=e2a"
UrlBuild := []string {SearchUrl, MovieSearch, apiKey}
fmt.Println(UrlBuild)

我得到了以下错误:

/main.go:71: cannot use MovieSearch (type []string) as type string in array or slice literal

MovieSearch 是来自输入表单的数据。它是搜索关键字。

一旦我有了一个字符串,我就可以将其传递给一个函数,该函数会进行API调用。

完整的函数如下:

func searchHandler(w http.ResponseWriter, r *http.Request) {
    display(w, "search", &Page{Title: "Search"})
    fmt.Println("method:", r.Method) 
    r.ParseForm()
    fmt.Println("GetSearchKey:", r.Form["GetSearchKey"])
    
    for key, values := range r.Form {   // 遍历map
        for _, value := range values {    // 遍历[]string
            fmt.Println(key, value)
        }
    }
    
    var SearchUrl = "https://api.themoviedb.org/3/search/movie?query="
    var MovieSearch []string = r.Form["GetSearchKey"]
    var apiKey = "&api_key=ewrfwrfwrcwerc"
    UrlBuild := []string {SearchUrl, MovieSearch, apiKey}
    fmt.Println(UrlBuild)
    
    fmt.Println(reflect.TypeOf(r.Form["GetSearchKey"]))
}

错误出现在这一行:

UrlBuild := []string {SearchUrl, MovieSearch, apiKey}
英文:

In GoLang I am looping through my form data like this,

for key, values := range r.Form {   // range over map
    for _, value := range values {    // range over []string
        fmt.Println(key, value)
    }
}

I can print the data out to the terminal like this but I need this data to be a string so I can access it from outside of the for loop.

How can I Put this in a variable that I can call outside of the for loop when the loop is finished?

My goal here is to build a url by joining these three strings

var SearchUrl = "https://api.themoviedb.org/3/search/movie?query="
var MovieSearch []string = r.Form["GetSearchKey"]   
var apiKey = "&api_key=e2a"
UrlBuild := []string {SearchUrl, MovieSearch, apiKey}
fmt.Println(UrlBuild) 

I get this error

/main.go:71: cannot use MovieSearch (type []string) 
as type string in array or slice literal

MovieSearch is coming from the input form. It is the search keywords.

Once I have one string I can pass this to a function that makes the api call.

The full function

func searchHandler(w http.ResponseWriter, r *http.Request) {
  display(w, "search", &Page{Title: "Search"})
   fmt.Println("method:", r.Method) 
        r.ParseForm()
        fmt.Println("GetSearchKey:", r.Form["GetSearchKey"])
     
for key, values := range r.Form {   // range over map
for _, value := range values {    // range over []string
    fmt.Println(key, value)

  }
}

var SearchUrl = "https://api.themoviedb.org/3/search/movie?query="
 var MovieSearch []string = r.Form["GetSearchKey"]   
var apiKey = "&api_key=ewrfwrfwrcwerc"
UrlBuild := []string {SearchUrl, MovieSearch, apiKey}
fmt.Println(UrlBuild)

fmt.Println(reflect.TypeOf(r.Form["GetSearchKey"] ))
}

The error comes from this line,

UrlBuild := []string {SearchUrl, MovieSearch, apiKey}

答案1

得分: 2

你不能在一个切片内部再使用切片。

func ArrayToString(array []string) string {
    str := strings.Join(array, "")
    return str
}

UrlBuild := []string {SearchUrl, ArrayToString(MovieSearch), apiKey}
fmt.Println(UrlBuild) 
UrlBuildString := ArrayToString(UrlBuild)

或者

UrlBuildString := ArrayToString([]string{SearchUrl, ArrayToString(MovieSearch), apiKey})

完整代码如下:

func ArrayToString(array []string) string {
    str := strings.Join(array, "")
    return str
}

func searchHandler(w http.ResponseWriter, r *http.Request) {
    display(w, "search", &Page{Title: "Search"})
    fmt.Println("method:", r.Method) 
    r.ParseForm()
    fmt.Println("GetSearchKey:", r.Form["GetSearchKey"])

    for key, values := range r.Form {   // range over map
        for _, value := range values {    // range over []string
            fmt.Println(key, value)
        }
    }

    var SearchUrl = "https://api.themoviedb.org/3/search/movie?query="
    var MovieSearch []string = r.Form["GetSearchKey"]   
    var apiKey = "&api_key=ewrfwrfwrcwerc"
    UrlBuild := []string {SearchUrl, ArrayToString(MovieSearch), apiKey}
    fmt.Println(UrlBuild)
    OUTPUT_STRING := ArrayToString(UrlBuild)
}
英文:

You cannot have a slice within a slice.

func ArrayToString(array []string) string {
	str := strings.Join(array, "")
	return str

}
UrlBuild := []string {SearchUrl, ArrayToString(MovieSearch), apiKey}
fmt.Println(UrlBuild) 
UrlBuildString := ArrayToString(UrlBuild)

OR

UrlBuildString := ArrayToString([]string{SearchUrl, ArrayToString(MovieSearch), apiKey}

__FULL

func ArrayToString(array []string) string {
	str := strings.Join(array, "")
	return str

}
func searchHandler(w http.ResponseWriter, r *http.Request) {
  display(w, "search", &Page{Title: "Search"})
   fmt.Println("method:", r.Method) 
        r.ParseForm()
        fmt.Println("GetSearchKey:", r.Form["GetSearchKey"])

for key, values := range r.Form {   // range over map
for _, value := range values {    // range over []string
    fmt.Println(key, value)

  }
}

var SearchUrl = "https://api.themoviedb.org/3/search/movie?query="
 var MovieSearch []string = r.Form["GetSearchKey"]   
var apiKey = "&api_key=ewrfwrfwrcwerc"
UrlBuild := []string {SearchUrl, ArrayToString(MovieSearch), apiKey}
fmt.Println(UrlBuild)
OUTPUT_STRING := ArrayToString(UrlBuild)
}

答案2

得分: 1

这个问题似乎并不那么糟糕,尽管我可能对问题有所误解。有很多方法可以构建这些字符串。

考虑以下使用字符串连接的方法(较慢):

s := []string{}
for key, values := range r.Form {   // 遍历映射
    for _, value := range values {    // 遍历 []string
        s = append(s, fmt.Sprintf("%s, %s", key, value))
    }
}
data := strings.Join(s, ";")

这里有更多关于字符串连接的示例:http://herman.asia/efficient-string-concatenation-in-go

英文:

This problem doesn't seem so bad, though I may be misunderstanding the question. There are many ways to build up these strings.

Consider the following approach using concatenation (slow):

s := []string{}
for key, values := range r.Form {   // range over map
    for _, value := range values {    // range over []string
        s = append(s, fmt.Sprintf("%s, %s", key, value))
    }
}
data := strings.Join(s, ";")

More examples of concat are seen here: http://herman.asia/efficient-string-concatenation-in-go

huangapple
  • 本文由 发表于 2016年3月14日 07:33:59
  • 转载请务必保留本文链接:https://go.coder-hub.com/35977267.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定