Add a variable to a class instance at runtime: Difference between revisions

Added Go
(Removed {{omit from|Go}} template as this task can be simulated using the built-in map type.)
(Added Go)
Line 469:
main \ => Now is the time 3.14159
</lang>
 
=={{header|Go}}==
{{trans|Kotlin}}
<br>
Firstly, Go doesn't have classes or class variables but does have structs (an analogous concept) which consist of fields.
 
Adding fields to a struct at runtime is not possible as Go is a statically typed, compiled language and therefore the names of all struct fields need to be known at compile time.
 
However, as in the case of Groovy and Kotlin, we can ''make it appear'' as though fields are being added at runtime by using the built-in map type. For example:
<lang go>package main
 
import (
"bufio"
"fmt"
"log"
"os"
)
 
type SomeStruct struct {
runtimeFields map[string]string
}
 
func check(err error) {
if err != nil {
log.Fatal(err)
}
}
 
func main() {
ss := SomeStruct{make(map[string]string)}
scanner := bufio.NewScanner(os.Stdin)
fmt.Println("Create two fields at runtime: ")
for i := 1; i <= 2; i++ {
fmt.Printf(" Field #%d:\n", i)
fmt.Print(" Enter name : ")
scanner.Scan()
name := scanner.Text()
fmt.Print(" Enter value : ")
scanner.Scan()
value := scanner.Text()
check(scanner.Err())
ss.runtimeFields[name] = value
fmt.Println()
}
for {
fmt.Print("Which field do you want to inspect ? ")
scanner.Scan()
name := scanner.Text()
check(scanner.Err())
value, ok := ss.runtimeFields[name]
if !ok {
fmt.Println("There is no field of that name, try again")
} else {
fmt.Printf("Its value is '%s'\n", value)
return
}
}
}</lang>
 
{{out}}
Sample input/output:
<pre>
Create two fields at runtime:
Field #1:
Enter name : a
Enter value : rosetta
 
Field #2:
Enter name : b
Enter value : 64
 
Which field do you want to inspect ? a
Its value is 'rosetta'
</pre>
 
=={{header|Groovy}}==
9,490

edits