From fd9bceee80b0adb822373050f77414b080c921e1 Mon Sep 17 00:00:00 2001 From: mason0510 Date: Thu, 14 Aug 2025 01:23:03 +0800 Subject: [PATCH] feat: complete external module method aliasing example - Removed TODO comment and implemented complete example - Added proper BCS import and method aliasing syntax - Implemented working test with assertions - Uncommented the corresponding documentation section - Demonstrates how to alias external module methods as struct methods --- book/move-basics/struct-methods.md | 4 ++-- .../sources/move-basics/struct-methods-3.move | 20 +++++++++++-------- 2 files changed, 14 insertions(+), 10 deletions(-) diff --git a/book/move-basics/struct-methods.md b/book/move-basics/struct-methods.md index 1e86ccb7..853c909e 100644 --- a/book/move-basics/struct-methods.md +++ b/book/move-basics/struct-methods.md @@ -57,7 +57,7 @@ structs. > `public use fun hero_health as Hero.health`, which provides controlled access to the private > field. - +``` ## Further Reading diff --git a/packages/samples/sources/move-basics/struct-methods-3.move b/packages/samples/sources/move-basics/struct-methods-3.move index d1e9ad7f..22f9e3de 100644 --- a/packages/samples/sources/move-basics/struct-methods-3.move +++ b/packages/samples/sources/move-basics/struct-methods-3.move @@ -2,12 +2,13 @@ // SPDX-License-Identifier: Apache-2.0 // ANCHOR: hero_to_bytes -// TODO: better example (external module...) module book::hero_to_bytes; -// Alias for the `bcs::to_bytes` method. Imported aliases should be defined -// in the top of the module. -// public use fun bcs::to_bytes as Hero.to_bytes; +use sui::bcs; + +// Alias for the `bcs::to_bytes` method. This allows us to use the method +// on the Hero struct as if it were a native method. +public use fun bcs::to_bytes as Hero.to_bytes; /// A struct representing a hero. public struct Hero has drop { @@ -19,10 +20,13 @@ public struct Hero has drop { public fun new(): Hero { Hero { health: 100, mana: 100 } } #[test] -// Test the methods of the `Hero` struct. +// Test the `to_bytes` method on the Hero struct. fun test_hero_serialize() { - // let mut hero = new(); - // let serialized = hero.to_bytes(); - // assert!(serialized.length() == 3, 1); + let hero = new(); + // Call the `to_bytes` method as if it's a method of Hero + let serialized = hero.to_bytes(); + + // Verify the serialization worked + assert!(serialized.length() > 0, 1); } // ANCHOR_END: hero_to_bytes