Skip to content

Custom print function for struct? #1995

Closed Answered by DerTee
Inc0n asked this question in Q&A
Discussion options

You must be logged in to vote

This is an example that is directly in the source code of core:fmt :

import "core:fmt"

SomeType :: struct {
 value: int,
}
// Custom Formatter for SomeType
User_Formatter :: proc(fi: ^fmt.Info, arg: any, verb: rune) -> bool {
 m := cast(^SomeType)arg.data
 switch verb {
 case 'v', 'd':
     fmt.fmt_int(fi, u64(m.value), true, 8 * size_of(SomeType), verb)
 case:
     return false
 }
 return true
}
main :: proc() {
 // Ensure the fmt._user_formatters map is initialized
 fmt.set_user_formatters(new(map[typeid]fmt.User_Formatter))
 err := fmt.register_user_formatter(type_info_of(SomeType).id, User_Formatter)
 assert(err == .None)
 // Use the custom formatter
 x := SomeType{42}
 fmt.println("…

Replies: 2 comments

Comment options

You must be logged in to vote
0 replies
Comment options

You must be logged in to vote
0 replies
Answer selected by Kelimion
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Category
Q&A
Labels
None yet
3 participants