gpt4 book ai didi

metaprogramming - 使用 `FALLBACK` 时如何知道是否返回左值?

转载 作者:行者123 更新时间:2023-12-04 13:56:22 25 4
gpt4 key购买 nike

我怎么知道在使用 FALLBACK 时我是否真的需要返回一个 l 值? ?

我正在使用 return-rw但我只想使用 return在可能的情况。我想跟踪我是否真的修改过 %!attrs或仅在 FALLBACK 时才读取值被称为。

或者(替代计划 B)我可以附加一个回调或类似于我的 %!attrs 的东西吗?监控变化?

class Foo {
has %.attrs;
submethod BUILD { %!attrs{'bar'} = 'bar' }

# multi method FALLBACK(Str:D $name, *@rest) {
# say 'read-only';
# return %!attrs{$name} if %!attrs«$name»:exists;
# }

multi method FALLBACK(Str:D $name, *@rest) {
say 'read-write';
return-rw %!attrs{$name} if %!attrs«$name»:exists;
}
}

my $foo = Foo.new;
say $foo.bar;

$foo.bar = 'baz';
say $foo.bar;

最佳答案

这感觉有点像一个 X-Y 问题,所以让我们简化这个例子,看看这个答案是否有助于你的决定。

首先:如果您返回散列中不存在的键的“值”,实际上您正在返回一个容器,当分配给时,该容器将自动激活散列中的键:

my %hash;
sub get($key) { return-rw %hash{$key} }
get("foo") = 42;
dd %hash; # Hash %hash = {:foo(42)}

请注意,您需要使用 return-rw在这里确保返回实际的容器,而不仅仅是容器中的值。或者,您可以使用 is raw trait,它允许你只设置最后一个值:
my %hash;
sub get($key) is raw { %hash{$key} }
get("foo") = 42;
dd %hash; # Hash %hash = {:foo(42)}

请注意,您不应该使用 return在那种情况下,因为它仍然会再次去容器化。

回到你的问题:

I want to track if I've actually modified %!attrs or have only just read the value when FALLBACK was called.


class Foo {
has %!attrs;
has %!unexpected;

method TWEAK() { %!attrs<bar> = 'bar' }

method FALLBACK(Str:D $name, *@rest) is raw {
if %!attrs{$name}:exists {
%!attrs{$name}
}
else {
%!unexpected{$name}++;
Any
}
}
}

这将返回在散列中找到的容器,或记录对未知 key 的访问并返回不可变的 Any .

关于计划 B,记录更改:为此您可以使用 Proxy反对。

希望这对您的追求有所帮助。

关于metaprogramming - 使用 `FALLBACK` 时如何知道是否返回左值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58071806/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com