Go:如何在 Go 中使用 func() bool 参数?

Go: How to use the func() bool arguments in go?

这是来自 Go blackfriday 包的示例代码:

package main

import (
    "bytes"
    "fmt"
    "github.com/russross/blackfriday"
)

func main() {

input := []byte(`##Title

- another paragragh

This is a being rendered in a custom way.
`)

    htmlFlags := 0
    renderer := &renderer{Html: blackfriday.HtmlRenderer(htmlFlags, "", "").(*blackfriday.Html)}

    extensions := 0

    unsanitized := blackfriday.Markdown(input, renderer, extensions)
    os.Stdout.Write(unsanitized)
}

// renderer implements blackfriday.Renderer and reuses blackfriday.Html for the most part,
// except overriding Link rendering.
type renderer struct {
    *blackfriday.Html
}

func (options *renderer) Header(out *bytes.Buffer, text func() bool, level int, id string) {
    fmt.Fprintf(out, "<custom link %q to %q>", content, link)
}

代码的目的是自定义输出HTML的link属性。

我尝试做同样的事情,但使用了 p 个标签:

func (options *renderer) Paragraph(out *bytes.Buffer, text func() bool) {
    fmt.Fprintf(out, "<p class='custom'>%q</p>", text)
}

但输出是这样的:

<h1>Title</h1>

<ul>
<li>another paragragh</li>
</ul>
<p class='custom'>%!q(func() bool=0x80a15d0)</p>

所以我不知道如何输出实际的文本 (This is a being rendered in a custom way.)。有什么想法吗?

这是函数的源代码:

func (options *Html) Paragraph(out *bytes.Buffer, text func() bool) {
    marker := out.Len()
    doubleSpace(out)

    out.WriteString("<p>")
    if !text() {
        out.Truncate(marker)
        return
    }
    out.WriteString("</p>\n")
}

我相信你需要做的就是打电话 text

func (options *renderer) Paragraph(out *bytes.Buffer, text func() bool) {
    fmt.Fprintf(out, "<p class='custom'>%q</p>\n", text())
}

我认为你对函数的用法是错误的。

看看 Html.Paragraph 并覆盖它。

也许看起来像:

func (options *renderer) Paragraph(out *bytes.Buffer, text func() bool) {
    marker := out.Len()
    doubleSpace(out) 

    out.WriteString("<p class='custom'>")
    if !text() {
        out.Truncate(marker)
        return
    }
    out.WriteString("</p>\n")
}