how can a GPIO of stm32 have many alternative functions?
Microcontrollers typically are designed around compromises on pin-count versus desired functions.

Thus, there will typically be a set of configuration ports or configuration registers, which define for the microcontroller how a given pin should behave. At a simplistic level, picture the parallel with a GPIO being used as input or as output, depending on configuration.

If such polymorphic functionality of pins were not implemented, an MCU would need many many more pins than they usually have, quickly getting into the realms of the impractical.

If an application needs a pin to be used for different functions at different points in code, typically there is set-up code written as part of the application, before each usage block, setting the configuration registers accordingly. Consider the GPIO-as-input/output example above.