如何概括对struct字段的访问?

时间:2017-11-01 06:53:13

标签: rust

我尝试从两个流(由迭代器表示)中找到差异以供以后分析,下面的代码工作正常,但在更新{{1}中的值时看起来有点丑陋且容易出错(复制粘贴!) } 功能。假设源是物质,有没有办法概括它?

update_v?

2 个答案:

答案 0 :(得分:1)

不是为每个字段编写一个函数,而是接收一对Fn作为参数:

  • fn(&S) -> Option<Data>,可用于替换此条件

    if e.get().v1 == new_variant { /* ... */ }
    

    用这个

    if getter(e.get()) == new_variant { /* ... */ }
    
  • fn(&mut S, Option<Data>) -> (),取代

    existing.v2 = new_variant;
    

    setter(&mut existing, new_variant);
    

然后在通话网站上你传递了一对像这样的lambdas

  • Getter:|d| d.v1
  • Setter:|s, d| s.v2 = d

反之亦然另一个功能。

如果你想保留update_v1update_v2函数名,只需将它们作为包装器写入这个自动传递正确lambda的新通用函数。

答案 1 :(得分:0)

您可以创建特征以促进访问结构的不同方式。

An error occurred while calling method 'BuildWebHost' on class 'Program'. Continuing without the application service provider. Error: Invalid object name 'Clients'.
No DbContext named 'ConfigurationDbContext' was found.

Full code