CodeBlanks Logo Icon CodeBlanks

Plugin symbol

Learn to get an exported symbol with Lookup.

Using the symbol

The result of Lookup is a plugin.Symbol. For a function you type-assert to the function type; for a variable, to a pointer to its type:

selam := sym.(func(string) string)
fmt.Println(selam("Ada"))

surum := vsym.(*string)  // pointer for a variable
fmt.Println(*surum)

A contract through interfaces

A tidier approach: the plugin exports a value that satisfies an interface and the main program asserts to that interface. The interface is defined in a shared package:

type Komut interface { Calistir() string }

k := sym.(Komut)
fmt.Println(k.Calistir())

Practice Type assertion

Declare var sym any = func(n int) int { return n + 1 } to imitate a plugin symbol. Convert it with sym.(func(int) int) and print f(9).

Starter code

main.go
package main

import "fmt"

func main() {
    // buraya yaz
}

Sample solution

main.go
package main

import "fmt"

func main() {
    var sym any = func(n int) int { return n + 1 }
    f := sym.(func(int) int)
    fmt.Println(f(9))
}

Expected output

10

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 If the plugin has <code>var Surum = "1.0"</code>, which type is the Lookup result asserted to?

  • string
  • func() string
  • []byte
  • *string Correct answer

Explanation: Variable symbols come back as pointers, so the main program can read and change the variable.

2 Convert to a function

Question
f := sym.(____)
fmt.Println(f(3))
Answer
f := sym.(func(int) int)
fmt.Println(f(3))

Explanation: A function symbol is type-asserted to its own signature.

3 Symbol and assertion

Term Meaning
func Selam(string) string func(string) string
var Surum string *string
var Sayac int *int
var Eklenti Komut The Komut interface

All lessons in Advanced