首页 > 解决方案 > 关闭不返回所需的输出

问题描述

我想知道为什么我的函数不返回这些行。我正在使用闭包,我的目标是显示解码文本中的每一行。我能够使用 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从文本中。

标签: functiongoclosures

解决方案


您必须调用该函数:

func main() {
    fmt.Println(getLine(base64Decode())())
}

推荐阅读