There is a code

func ClearScreen(mode *int) string{ mode = defaultValue(mode, 2).(*int) return fmt.Sprintf("%s%dK", CSI, *mode) } func defaultValue(arg *T, value T) *T{ if arg == nil{ arg = new(T) *arg = value } return arg } 

The defaultValue function is not only used with the int data type, so I declared it to accept the T data type T interface{} ( type T interface{} ). I use pointers so that ClearScreen(nil) can do this (that is, use the default value for the mode argument)

If this can be implemented in a more obvious way, I will be glad if you can help. If this method is not bad, then how to modify it? Golang study not so long ago.

PS CSI - string constant

  • 2
    Guo do not chop and not Python. The sooner you refuse such constructions, the better. In Go they take root extremely badly and bring nothing but suffering. The first decent gopher will rewrite this code for something like this . - Ainar-G 5:38 pm
  • @Ainar-g, thank you. We'll have to write a bunch of constants ... oh - Mr Morgan

1 answer 1

As Ainar-G already wrote, such constructions in Go are undesirable. The rewritten code might look like this:

 const defaultMode = 2 // ClearScreen clears the screen. Use -1 for default mode. func ClearScreen(mode int) string { if mode == -1 { mode = defaultMode } return fmt.Sprintf("%s%dK", CSI, mode) }