|
| 1 | +// Copyright 2025 CloudWeGo Authors |
| 2 | +// |
| 3 | +// Licensed under the Apache License, Version 2.0 (the "License"); |
| 4 | +// you may not use this file except in compliance with the License. |
| 5 | +// You may obtain a copy of the License at |
| 6 | +// |
| 7 | +// https://www.apache.org/licenses/LICENSE-2.0 |
| 8 | +// |
| 9 | +// Unless required by applicable law or agreed to in writing, software |
| 10 | +// distributed under the License is distributed on an "AS IS" BASIS, |
| 11 | +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 12 | +// See the License for the specific language governing permissions and |
| 13 | +// limitations under the License. |
| 14 | + |
| 15 | +/** |
| 16 | + * Copyright 2025 ByteDance Inc. |
| 17 | + * |
| 18 | + * Licensed under the Apache License, Version 2.0 (the "License"); |
| 19 | + * you may not use this file except in compliance with the License. |
| 20 | + * You may obtain a copy of the License at |
| 21 | + * |
| 22 | + * https://www.apache.org/licenses/LICENSE-2.0 |
| 23 | + * |
| 24 | + * Unless required by applicable law or agreed to in writing, software |
| 25 | + * distributed under the License is distributed on an "AS IS" BASIS, |
| 26 | + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 27 | + * See the License for the specific language governing permissions and |
| 28 | + * limitations under the License. |
| 29 | + */ |
| 30 | + |
| 31 | +pub trait Addable { |
| 32 | + fn id() -> i64; |
| 33 | + fn add(&self, b: i64) -> i64; |
| 34 | +} |
| 35 | + |
| 36 | +pub struct AnyInt(i64); |
| 37 | + |
| 38 | +impl AnyInt { |
| 39 | + pub fn id() -> i64 { |
| 40 | + 0 |
| 41 | + } |
| 42 | + pub fn add(&self, b: i64) -> i64 { |
| 43 | + self.0 + b |
| 44 | + } |
| 45 | +} |
| 46 | + |
| 47 | +impl Addable for AnyInt { |
| 48 | + fn add(&self, b: i64) -> i64 { |
| 49 | + // use the method defined in the struct |
| 50 | + self.add(b) |
| 51 | + } |
| 52 | + fn id() -> i64 { |
| 53 | + // use the method defined in the struct |
| 54 | + AnyInt::id() |
| 55 | + } |
| 56 | +} |
| 57 | + |
| 58 | +fn add_trait<T: Addable>(i: T, v: i64) { |
| 59 | + println!("{}", i.add(v)) |
| 60 | +} |
| 61 | + |
| 62 | +#[test] |
| 63 | +fn test() { |
| 64 | + add_trait(AnyInt(1), 2); |
| 65 | +} |
0 commit comments