function - 关闭不返回所需的输出
问题描述
我想知道为什么我的函数不返回这些行。我正在使用闭包,我的目标是显示解码文本中的每一行。我能够使用 Python 实现这一目标。
这是我的 Python 代码:
def get_line():
lines = base64_decode()
index = 0
def closure():
nonlocal index
def go_next():
nonlocal index
next_line = line[index]
index += 1
return next_line
if index != len(lines):
return go_next()
else:
index = 0
return go_next()
return closure
这是我的 Go 代码:
package main
import (
"encoding/base64"
"fmt"
"log"
"strings"
)
func base64Decode() string {
str := "REDACTED"
data, err := base64.StdEncoding.DecodeString(str)
if err != nil {
log.Fatal("Error:", err)
}
return string(data)
}
func getLine(str string) func() string {
i := 0
lines := strings.Split(str, "\n")
return func() string {
if i != len(lines) {
nextLine := lines[i]
i++
return nextLine
}
return ""
}
}
func main() {
fmt.Println(getLine(base64Decode()))
}
当我运行它时会发生什么,它只打印:0x1095850
而不是This is the first line
从文本中。
解决方案
您必须调用该函数:
func main() {
fmt.Println(getLine(base64Decode())())
}
推荐阅读
- microsoft-graph-api - 获取对话成员导致错误请求 (Microsoft Graph)
- c - Sprintf 将大量数字变为“4”
- linux - 使用 awk、tr 或 sed 从文本文件中删除新行以使文本出现在单行上
- python - 如何使用保存在另一个 DataFrame 中的指令对 Python DataFrame 进行算术运算?
- python - 使用熊猫在数据框之间进行值查找?
- flutter - easy_localization 具有其他语言的键的后备值
- jasper-reports - Jasper 报告标题在新页面上
- mysql - 如何在MYSQL中创建一个存储过程,该过程在开始日期和结束日期之间获取销售的开始日期和结束日期
- java - 编写一个不能使用递归的红黑树程序插入
- android - How to edit Virtual Device? Android Studio - Java