Home >Backend Development >Golang >How to Extract the Literal String Value from a Go AST's `ast.BasicLit` Node?

How to Extract the Literal String Value from a Go AST's `ast.BasicLit` Node?

Barbara Streisand
Barbara StreisandOriginal
2024-12-26 11:45:10944browse

How to Extract the Literal String Value from a Go AST's `ast.BasicLit` Node?

How to Retrieve String Literal Value from Go AST

When traversing a Go syntax tree to identify calls to a specific function that takes a string literal argument, you may encounter an ast.BasicLit node with Kind == token.STRING. However, this node's value field contains Go syntax rather than the actual string value it represents.

To obtain the string's literal value, use the strconv.Unquote() function. However, note that this function only unquotes strings that are enclosed in quotes. If the string in the ast.BasicLit is not quoted, you must manually prepend it with the appropriate quote character.

Example:

package main

import (
    "fmt"
    "go/ast"
    "go/parser"
    "go/token"
    "strconv"
)

func main() {
    fset := token.NewFileSet()
    node, _ := parser.ParseExpr(`` + "Hello World!" + `"`)

    switch node := node.(type) {
    case *ast.BasicLit:
        fmt.Println(strconv.Unquote(node.Value)) // Prints "Hello World!"
    }
}

Output:

Hello World!

The above is the detailed content of How to Extract the Literal String Value from a Go AST's `ast.BasicLit` Node?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn