Solidity 中的结构工厂

Struct Factories in Solidity

所以我正在使用 Solidity 开发一个 DApp,并且想利用关注点分离。我有一个添加和删除用户的合同。我的用户是结构类型。所以我想我会写另一个合同,一个使用工厂设计模式并分离关注点的 UserFactory 合同,因为 UserManager 不应该负责创建用户。不幸的是,除非我启用 ABIEncoderV2,否则我无法 return 从我的工厂合同中构建结构,但由于这是一个实验性功能,它不会在生产中工作。看来对于 Solidity 我需要找到一种不同的方法来解决这个设计问题。是否有解决 Solidity 的方法?任何帮助将不胜感激。提前致谢!

您可以 return 用户属性的元组:

mapping(uint -> User)
type User struct {
   string name;
   string address;
   uint age;
}
function getUser(uint key) public constant returns(string,address, uint) {
     return (users[key].name, users[key].address, users[key].age;
}

但我相信使用 ABIEncoderV2 是安全的。 Here参考官方文档

ABIEncoderV2 The new ABI encoder is able to encode and decode arbitrarily nested arrays and structs. It might produce less optimal code and has not received as much testing as the old encoder, but is considered non-experimental as of Solidity 0.6.0. You still have to explicitly activate it using pragma experimental ABIEncoderV2; - we kept the same pragma, even though it is not considered experimental anymore