2021-04-12 18:32:51 +02:00
|
|
|
import context
|
|
|
|
|
2021-09-27 16:52:20 +02:00
|
|
|
const not_found_value = &Value{
|
|
|
|
val: 'key not found'
|
|
|
|
}
|
|
|
|
|
|
|
|
struct Value {
|
|
|
|
val string
|
|
|
|
}
|
2021-04-12 18:32:51 +02:00
|
|
|
|
|
|
|
// This example demonstrates how a value can be passed to the context
|
|
|
|
// and also how to retrieve it if it exists.
|
|
|
|
fn test_with_value() {
|
2021-09-27 16:52:20 +02:00
|
|
|
f := fn (ctx context.Context, key context.Key) &Value {
|
2021-04-12 18:32:51 +02:00
|
|
|
if value := ctx.value(key) {
|
2021-09-27 16:52:20 +02:00
|
|
|
match value {
|
|
|
|
Value {
|
|
|
|
return value
|
|
|
|
}
|
|
|
|
else {}
|
2021-04-12 18:32:51 +02:00
|
|
|
}
|
|
|
|
}
|
2021-09-27 16:52:20 +02:00
|
|
|
return not_found_value
|
2021-04-12 18:32:51 +02:00
|
|
|
}
|
|
|
|
|
2021-09-27 16:52:20 +02:00
|
|
|
key := 'language'
|
|
|
|
value := &Value{
|
|
|
|
val: 'VAL'
|
|
|
|
}
|
|
|
|
ctx := context.with_value(context.background(), key, value)
|
2021-04-12 18:32:51 +02:00
|
|
|
|
|
|
|
assert value == f(ctx, key)
|
2021-09-27 16:52:20 +02:00
|
|
|
assert not_found_value == f(ctx, 'color')
|
2021-04-12 18:32:51 +02:00
|
|
|
}
|