-
Notifications
You must be signed in to change notification settings - Fork 566
Built‐in Functions
XGo extends Go's standard built-in functions with additional capabilities for common operations. This document provides a comprehensive reference for all built-in functions available in XGo.
XGo supports all standard Go built-in functions:
append(slice []Type, elems ...Type) []Type
Appends elements to the end of a slice. Returns the updated slice.
numbers := []int{1, 2, 3}
numbers = append(numbers, 4, 5)
echo numbers // Output: [1 2 3 4 5]len(v Type) int
Returns the length of arrays, slices, maps, strings, or channels.
echo len("Hello") // Output: 5
echo len([]int{1,2,3}) // Output: 3cap(v Type) int
Returns the capacity of arrays, slices, or channels.
s := make([]int, 3, 5)
echo len(s) // Output: 3
echo cap(s) // Output: 5make(t Type, size ...IntegerType) Type
Allocates and initializes slices, maps, or channels.
slice := make([]int, 5, 10) // length 5, capacity 10
m := make(map[string]int) // empty map
ch := make(chan int, 10) // buffered channelcopy(dst, src []Type) int
Copies elements from source to destination slice. Returns the number of elements copied.
src := []int{1, 2, 3}
dst := make([]int, 3)
n := copy(dst, src)
echo n // Output: 3
echo dst // Output: [1 2 3]delete(m map[Type]Type1, key Type)
Deletes a key from a map.
m := map[string]int{"a": 1, "b": 2}
delete(m, "a")
echo m // Output: map[b:2]clear[T ~[]Type | ~map[Type]Type1](t T)
Clears all entries in maps or sets slice elements to zero values.
m := map[string]int{"a": 1, "b": 2}
clear(m)
echo len(m) // Output: 0new(Type) *Type
Allocates memory and returns a pointer to zero value.
p := new(int)
echo *p // Output: 0max[T cmp.Ordered](x T, y ...T) T
Returns the largest value among arguments.
echo max(1, 5, 3, 9, 2) // Output: 9
echo max(3.14, 2.71) // Output: 3.14min[T cmp.Ordered](x T, y ...T) T
Returns the smallest value among arguments.
echo min(1, 5, 3, 9, 2) // Output: 1
echo min(3.14, 2.71) // Output: 2.71complex(r, i FloatType) ComplexType
Constructs a complex number from real and imaginary parts.
c := complex(3.0, 4.0)
echo c // Output: (3+4i)real(c ComplexType) FloatType
Returns the real part of a complex number.
c := 3 + 4i
echo real(c) // Output: 3imag(c ComplexType) FloatType
Returns the imaginary part of a complex number.
c := 3 + 4i
echo imag(c) // Output: 4panic(v any)
Stops normal execution and begins panicking.
if value < 0 {
panic("negative value not allowed")
}recover() any
Recovers from a panic in deferred functions.
defer func() {
if r := recover(); r != nil {
println("Recovered from:", r)
}
}()close(c chan<- Type)
Closes a channel.
ch := make(chan int)
close(ch)XGo provides enhanced I/O functions with a cleaner API:
Echo(a ...any) (n int, err error)
Formats and writes to standard output with spaces between operands and a newline appended.
echo "Hello", "World" // Output: Hello World
echo 42, true, 3.14 // Output: 42 true 3.14Print(a ...any) (n int, err error)
Writes to standard output, adding spaces only when neither operand is a string.
print("Hello", "World") // Output: HelloWorld
print(1, 2, 3) // Output: 1 2 3Println(a ...any) (n int, err error)
Writes to standard output with spaces between operands and a newline appended.
println("Hello", "World") // Output: Hello WorldPrintf(format string, a ...any) (n int, err error)
Formats according to format specifier and writes to standard output.
printf("Name: %s, Age: %d\n", "Alice", 30)
// Output: Name: Alice, Age: 30Sprint(a ...any) string
Returns formatted string, adding spaces when neither operand is a string.
s := sprint("Hello", "World")
echo s // Output: HelloWorldSprintln(a ...any) string
Returns formatted string with spaces between operands and a newline.
s := sprintln("Hello", "World")
echo s // Output: "Hello World\n"Sprintf(format string, a ...any) string
Returns string formatted according to format specifier.
s := sprintf("Age: %d", 25)
echo s // Output: Age: 25Fprint(w io.Writer, a ...any) (n int, err error)
Writes to specified writer.
file, _ := create("output.txt")
fprint(file, "Hello", "World")Fprintln(w io.Writer, a ...any) (n int, err error)
Writes to specified writer with newline.
file, _ := create("output.txt")
fprintln(file, "Hello", "World")Fprintf(w io.Writer, format string, a ...any) (n int, err error)
Writes formatted output to specified writer.
file, _ := create("output.txt")
fprintf(file, "Count: %d\n", 42)Errorf(format string, a ...any) error
Creates formatted error. Supports %w verb for error wrapping.
err := errorf("failed to process: %w", originalError)Errorln(args ...any)
Formats and prints to standard error.
errorln("Warning:", "Something went wrong")Fatal(args ...any)
Formats and prints to standard error (typically exits program).
fatal("Critical error occurred")Open(name string) (*os.File, error)
Opens file for reading with O_RDONLY mode.
file, err := open("data.txt")
if err != nil {
errorln(err)
}
defer file.Close()Create(name string) (*os.File, error)
Creates or truncates file with mode 0o666.
file, err := create("output.txt")
if err != nil {
errorln(err)
}
defer file.Close()Type(i any) reflect.Type
Returns the reflection Type representing the dynamic type of i.
t := type(42)
echo t.Name() // Output: int
s := "hello"
echo type(s).Name() // Output: stringXGo provides convenient line reading utilities:
Lines(r io.Reader) osx.LineReader
Returns a LineReader for reading lines.
file, _ := open("data.txt")
for line in lines(file) {
echo line
}Blines(r io.Reader) osx.BLineReader
Returns a BLineReader for reading lines as byte slices.
file, _ := open("data.txt")
for line in blines(file) {
echo string(line)
}(r io.Reader).XGo_Enum() iox.LineIter
Returns a LineIter for iterating over lines (supports for in syntax).
file, _ := open("data.txt")
for line in file {
echo line
}When working with strings, XGo provides convenient method syntax for common operations.
(s string).Len() int
Returns the number of bytes in the string.
echo "Hello".len // Output: 5(s string).Count(substr string) int
Counts non-overlapping instances of substring.
echo "hello world".count("l") // Output: 3
echo "aaaa".count("aa") // Output: 2(s string).ToUpper() string
Converts all letters to uppercase.
echo "Hello".toUpper // Output: HELLO(s string).ToLower() string
Converts all letters to lowercase.
echo "Hello".toLower // Output: hello(s string).ToTitle() string
Converts all letters to title case.
echo "hello world".toTitle // Output: HELLO WORLD(s string).Capitalize() string
Capitalizes the first letter only.
echo "hello world".capitalize // Output: Hello world(s string).Repeat(count int) string
Returns string repeated count times.
echo "Ha".repeat(3) // Output: HaHaHa(s string).ReplaceAll(old, new string) string
Replaces all non-overlapping instances of old with new.
echo "Hello".replaceAll("l", "L") // Output: HeLLo(s string).Replace() string
Returns copy with replacements performed.
s := "hello world"
result := s.replace("world", "XGo", -1)
echo result // Output: hello XGo(s string).Trim(cutset string) string
Removes leading and trailing characters from cutset.
echo " hello ".trim(" ") // Output: hello
echo "!!hello!!".trim("!") // Output: hello(s string).TrimSpace() string
Removes leading and trailing whitespace.
echo " hello ".trimSpace // Output: hello(s string).TrimLeft(cutset string) string
Removes leading characters from cutset.
echo "###hello".trimLeft("#") // Output: hello(s string).TrimRight(cutset string) string
Removes trailing characters from cutset.
echo "hello###".trimRight("#") // Output: hello(s string).TrimPrefix(prefix string) string
Removes leading prefix if present.
echo "Hello World".trimPrefix("Hello ") // Output: World(s string).TrimSuffix(suffix string) string
Removes trailing suffix if present.
echo "file.txt".trimSuffix(".txt") // Output: file(s string).Fields() []string
Splits string around whitespace.
echo "hello world xgo".fields // Output: [hello world xgo](s string).Split(sep string) []string
Splits string around separator.
echo "a,b,c".split(",") // Output: [a b c](s string).SplitN(sep string, n int) []string
Splits string with count limit.
echo "a-b-c-d".splitN("-", 2) // Output: [a b-c-d](s string).SplitAfter(sep string) []string
Splits after each separator.
echo "a,b,c".splitAfter(",") // Output: [a, b, c](s string).SplitAfterN(sep string, n int) []string
Splits after separator with count limit.
echo "a,b,c,d".splitAfterN(",", 2) // Output: [a, b,c,d](s string).Index(substr string) int
Returns index of first instance of substring, or -1 if not found.
echo "hello".index("ll") // Output: 2
echo "hello".index("x") // Output: -1(s string).IndexByte(c byte) int
Returns index of first instance of byte.
echo "hello".indexByte('l') // Output: 2(s string).IndexRune(r rune) int
Returns index of first instance of rune.
echo "hello".indexRune('o') // Output: 4(s string).IndexAny(chars string) int
Returns index of first instance of any character from chars.
echo "hello".indexAny("aeiou") // Output: 1 (finds 'e')(s string).LastIndex(substr string) int
Returns index of last instance of substring.
echo "hello".lastIndex("l") // Output: 3(s string).LastIndexByte(c byte) int
Returns index of last instance of byte.
echo "hello".lastIndexByte('l') // Output: 3(s string).LastIndexAny(chars string) int
Returns index of last instance of any character.
echo "hello".lastIndexAny("aeiou") // Output: 4 (finds 'o')(s string).Contains(substr string) bool
Reports whether substring is present.
echo "hello".contains("ll") // Output: true
echo "hello".contains("xyz") // Output: false(s string).ContainsAny(chars string) bool
Reports whether any character from chars is present.
echo "hello".containsAny("aeiou") // Output: true(s string).ContainsRune(r rune) bool
Reports whether rune is present.
echo "hello".containsRune('e') // Output: true(s string).HasPrefix(prefix string) bool
Reports whether string begins with prefix.
echo "hello".hasPrefix("hel") // Output: true
echo "hello".hasPrefix("bye") // Output: false(s string).HasSuffix(suffix string) bool
Reports whether string ends with suffix.
echo "hello.txt".hasSuffix(".txt") // Output: true(s string).EqualFold(t string) bool
Reports case-insensitive equality.
echo "Hello".equalFold("hello") // Output: true(s string).Compare(b string) int
Returns 0 if equal, -1 if less, +1 if greater.
echo "abc".compare("abc") // Output: 0
echo "abc".compare("xyz") // Output: -1
echo "xyz".compare("abc") // Output: 1(s string).Quote() string
Returns double-quoted Go string literal.
echo "hello\nworld".quote // Output: "hello\nworld"(s string).Unquote() (string, error)
Interprets string as a quoted Go string literal.
s, err := `"hello\nworld"`.unquote
echo s // Output: hello
// world(s string).Int() (int, error)
Parses string as base-10 integer.
n, err := "42".int
if err == nil {
echo n // Output: 42
}(s string).Int64() (int64, error)
Parses string as 64-bit signed integer.
n, err := "9223372036854775807".int64
if err == nil {
echo n
}(s string).Uint64() (uint64, error)
Parses string as 64-bit unsigned integer.
n, err := "18446744073709551615".uint64
if err == nil {
echo n
}(s string).Float() (float64, error)
Parses string as 64-bit floating-point number.
f, err := "3.14159".float
if err == nil {
echo f // Output: 3.14159
}XGo provides String() methods for numeric types to easily convert numbers to strings.
(i int).String() string
Converts int to base-10 string.
echo 42.string // Output: 42(i int64).String() string
Converts int64 to base-10 string.
n := int64(123456789)
echo n.string // Output: 123456789(u uint64).String() string
Converts uint64 to base-10 string.
n := uint64(18446744073709551615)
echo n.string(f float64).String() string
Converts float64 to string using format 'g' with precision -1.
echo 3.14159.string // Output: 3.14159XGo provides method syntax for operations on string slices, making batch operations more convenient.
(v []string).Len() int
Returns the number of elements.
words := []string{"hello", "world"}
echo words.len // Output: 2(v []string).Cap() int
Returns the capacity.
words := make([]string, 2, 5)
echo words.cap // Output: 5(v []string).Join(sep string) string
Concatenates elements with separator.
words := []string{"hello", "world", "xgo"}
echo words.join(" ") // Output: hello world xgo
echo words.join(", ") // Output: hello, world, xgo(v []string).Capitalize() []string
Capitalizes first letter of each string.
words := []string{"hello", "world"}
echo words.capitalize // Output: [Hello World](v []string).ToTitle() []string
Title-cases all strings.
words := []string{"hello", "world"}
echo words.toTitle // Output: [HELLO WORLD](v []string).ToUpper() []string
Upper-cases all strings.
words := []string{"hello", "world"}
echo words.toUpper // Output: [HELLO WORLD](v []string).ToLower() []string
Lower-cases all strings.
words := []string{"HELLO", "WORLD"}
echo words.toLower // Output: [hello world](v []string).Repeat(count int) []string
Repeats each string count times.
words := []string{"ha", "ho"}
echo words.repeat(3) // Output: [hahaha hohoho](v []string).Replace(old, new string, n int) []string
Replaces occurrences in each string.
words := []string{"hello", "yellow"}
echo words.replace("ll", "LL", -1) // Output: [heLLo yeLLow](v []string).ReplaceAll(old, new string) []string
Replaces all occurrences in each string.
words := []string{"hello", "yellow"}
echo words.replaceAll("l", "L") // Output: [heLLo yeLLow](v []string).Trim(cutset string) []string
Trims each string.
words := []string{" hello ", " world "}
echo words.trim(" ") // Output: [hello world](v []string).TrimSpace() []string
Removes whitespace from each string.
words := []string{" hello ", " world "}
echo words.trimSpace // Output: [hello world](v []string).TrimLeft(cutset string) []string
Removes leading characters from each string.
words := []string{"###hello", "###world"}
echo words.trimLeft("#") // Output: [hello world](v []string).TrimRight(cutset string) []string
Removes trailing characters from each string.
words := []string{"hello###", "world###"}
echo words.trimRight("#") // Output: [hello world](v []string).TrimPrefix(prefix string) []string
Removes prefix from each string.
words := []string{"Mr. John", "Mr. Smith"}
echo words.trimPrefix("Mr. ") // Output: [John Smith](v []string).TrimSuffix(suffix string) []string
Removes suffix from each string.
files := []string{"file1.txt", "file2.txt"}
echo files.trimSuffix(".txt") // Output: [file1 file2]XGo allows calling many standard library functions as methods on their first argument. This provides a more fluent API while maintaining compatibility with Go's standard library. For example:
// Traditional Go style
s := strings.ToUpper("hello")
// XGo method style
s := "hello".toUpperBoth styles work in XGo, giving you flexibility in how you write your code.
In XGo, when calling methods or functions that take no arguments, you can omit the parentheses:
echo "Hello".toUpper // Without parentheses
echo "Hello".toUpper() // With parentheses (also valid)Both forms are equivalent and valid. This makes the code more concise and readable.
Functions that parse strings (Int, Int64, Uint64, Float, Unquote) return errors for invalid input. Always check the error return value:
n, err := "123abc".int
if err != nil {
errorln("Invalid number:", err)
} else {
echo n
}String operations in XGo are Unicode-aware, properly handling UTF-8 encoded text and runes:
echo "你好世界".len // Output: 12 (bytes)
echo len("你好世界") // Output: 12 (bytes)
echo "你好世界".count("好") // Output: 1When performing batch operations on string slices, the method syntax creates a new slice with transformed values:
// Creates a new slice with all strings uppercased
upper := words.toUpper
// Original slice unchanged
echo words // Original values
echo upper // Uppercased valuesXGo uses for in syntax for iterating over collections, which is more intuitive than Go's traditional for range:
// Iterate over slice
words := []string{"hello", "world", "xgo"}
for word in words {
echo word
}
// Iterate over file lines
file, _ := open("data.txt")
for line in file {
echo line
}