Cryptozombies第2课第13章:feedAndMultiply为何用keccak256比较字符串?
keccak256(_species) == keccak256("kitty") instead of direct string comparison in feedAndMultiply? Great question—this is a super common point of confusion when working through Cryptozombies, so let’s break it down clearly:
1. Solidity’s historical limitation on direct string equality checks
The Cryptozombies tutorial is built around older versions of Solidity, where you couldn’t directly compare two string values using ==. Strings are dynamically sized types, and the compiler didn’t natively support checking their equality straight out of the box. To work around this, developers relied on cryptographic hash functions to convert strings into fixed-length, comparable values.
2. How keccak256 solves this problem
keccak256 is a built-in cryptographic hash function in Solidity that takes any input (including strings) and outputs a unique 256-bit fixed-length hash. When you run:
keccak256(_species) == keccak256("kitty")
You’re converting both the input _species string and the literal "kitty" into their unique hash representations. If the original strings are identical, their hashes will match perfectly—this gives you a reliable way to check if the two strings are equal.
3. A quick note on newer Solidity versions
It’s worth mentioning that newer Solidity releases (0.8.17 and later) do support direct string equality checks with ==. But since Cryptozombies uses an older version for teaching foundational concepts, the hash-based comparison pattern is used here. Plus, this pattern is still widely used in legacy smart contract code, so it’s good to understand!
内容的提问来源于stack exchange,提问作者roytags

