我正在尝试学习Go(或Golang),但似乎无法正确完成。我有2个文本文件,每个文件包含一个单词列表。我正在尝试计算两个文件中存在的单词数量。
到目前为止,这是我的代码:
package main
import (
"fmt"
"log"
"net/http"
"bufio"
)
func stringInSlice(str string, list []string) bool {
for _, v := range list {
if v == str {
return true
}
}
return false
}
func main() {
// Texts URL
var list = "https://gist.githubusercontent.com/alexcesaro/c9c47c638252e21bd82c/raw/bd031237a56ae6691145b4df5617c385dffe930d/list.txt"
var url1 = "https://gist.githubusercontent.com/alexcesaro/4ebfa5a9548d053dddb2/raw/abb8525774b63f342e5173d1af89e47a7a39cd2d/file1.txt"
//Create storing arrays
var buffer [2000]string
var bufferUrl1 [40000]string
// Set a sibling counter
var sibling = 0
// Read and store text files
wordList, err := http.Get(list)
if err != nil {
log.Fatalf("Error while getting the url : %v", err)
}
defer wordList.Body.Close()
wordUrl1, err := http.Get(url1)
if err != nil {
log.Fatalf("Error while getting the url : %v", err)
}
defer wordUrl1.Body.Close()
streamList := bufio.NewScanner(wordList.Body)
streamUrl1 := bufio.NewScanner(wordUrl1.Body)
streamList.Split(bufio.ScanLines)
streamUrl1.Split(bufio.ScanLines)
var i = 0;
var j = 0;
//Fill arrays with each lines
for streamList.Scan() {
buffer[i] = streamList.Text()
i++
}
for streamUrl1.Scan() {
bufferUrl1[j] = streamUrl1.Text()
j++
}
//ERROR OCCURRING HERE :
// This code if i'm not wrong is supposed to compare through all the range of bufferUrl1 -> bufferUrl1 values with buffer values, then increment sibling and output FIND
for v := range bufferUrl1{
if stringInSlice(bufferUrl1, buffer) {
sibling++
fmt.Println("FIND")
}
}
// As a testing purpose thoses lines properly paste both array
// fmt.Println(buffer)
// fmt.Println(bufferUrl1)
}
但是现在,我的构建甚至还没有成功。我只收到以下消息:
.\hello.go:69: cannot use bufferUrl1 (type [40000]string) as type string in argument to stringInSlice
.\hello.go:69: cannot use buffer (type [2000]string) as type []string in argument to stringInSlice
[4000]string
。您打算使用v
(中的每个字符串bufferUrl1
)。但实际上,您打算使用第二个变量-第一个变量是在下面的代码中使用忽略的索引_
。[2000]string
不同于[]string
。在Go中,数组和切片不相同。阅读Go Slices:用法和内部知识。我已经将两个变量声明都更改为使用make使用具有相同初始长度的切片。这些是您需要进行编译才能进行的更改。
声明:
// Create storing slices
buffer := make([]string, 2000)
bufferUrl1 := make([]string, 40000)
和第69行的循环:
for _, s := range bufferUrl1 {
if stringInSlice(s, buffer) {
sibling++
fmt.Println("FIND")
}
}
作为旁注,请考虑使用地图而不是切片来buffer
进行更有效的查找,而不是遍历中的列表stringInSlice
。
https://play.golang.org/p/UcaSVwYcIw已修复以下注释(您将无法从Playground发出HTTP请求)。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句