2021-04-12 19:32:51 +03:00
|
|
|
import context
|
|
|
|
|
2021-09-27 17:52:20 +03:00
|
|
|
const not_found_value = &Value{
|
|
|
|
val: 'key not found'
|
|
|
|
}
|
|
|
|
|
|
|
|
struct Value {
|
|
|
|
val string
|
|
|
|
}
|
2021-04-12 19:32:51 +03: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 17:52:20 +03:00
|
|
|
f := fn (ctx context.Context, key context.Key) &Value {
|
2021-04-12 19:32:51 +03:00
|
|
|
if value := ctx.value(key) {
|
2021-09-27 17:52:20 +03:00
|
|
|
match value {
|
|
|
|
Value {
|
|
|
|
return value
|
|
|
|
}
|
|
|
|
else {}
|
2021-04-12 19:32:51 +03:00
|
|
|
}
|
|
|
|
}
|
2021-09-27 17:52:20 +03:00
|
|
|
return not_found_value
|
2021-04-12 19:32:51 +03:00
|
|
|
}
|
|
|
|
|
2021-09-27 17:52:20 +03:00
|
|
|
key := 'language'
|
|
|
|
value := &Value{
|
|
|
|
val: 'VAL'
|
|
|
|
}
|
|
|
|
ctx := context.with_value(context.background(), key, value)
|
2021-04-12 19:32:51 +03:00
|
|
|
|
|
|
|
assert value == f(ctx, key)
|
2021-09-27 17:52:20 +03:00
|
|
|
assert not_found_value == f(ctx, 'color')
|
2021-04-12 19:32:51 +03:00
|
|
|
}
|