Standard library / go/ast

go/ast.SliceExpr

Represents a two- or three-index slice expression. The example extracts the source span from a parsed file; no type checking is performed. Expected stdout: 'a[1:3]\n'.

Formal Syntax & Structure

go syntaxgo
type SliceExpr struct {  X      Expr  Lbrack token.Pos  Low    Expr  High   Expr  Max    Expr  Slice3 bool  Rbrack token.Pos}

Working Example

Example Snippetgo
package main
import (  "fmt"  "go/ast"  "go/parser"  "go/token")
func check(e error) {  if e != nil {    panic(e)  }}func parsed(src string) (*token.FileSet, *ast.File) {  fs := token.NewFileSet()  f, e := parser.ParseFile(fs, "demo.go", src, parser.ParseComments|parser.SkipObjectResolution)  check(e)  return fs, f}func find[T ast.Node](root ast.Node) T {  for n := range ast.Preorder(root) {    if x, ok := n.(T); ok {      return x    }  }  panic("node not found")}
func main() {  src := "package p\nvar x = a[1:3]"  fs, f := parsed(src)  n := find[*ast.SliceExpr](f)  fmt.Println(src[fs.Position(n.Pos()).Offset:fs.Position(n.End()).Offset])}
Go Reference