In the original “Star Trek,” for instance, one might note that Captain Kirk (William Shatner) wore a gold uniform. That was to denote his position in management. Other lower-ranking officers in gold uniforms were essentially on the “management track,” presumably learning about all departments on a starship and hoping to command a vessel of their own someday (or at least become a first officer).
Those in the red uniforms worked with the technical aspects of a ship. Scotty (James Doohan) and Uhura (Nichelle Nichols) dealt with machinery, engines, communication devices, etc. Red was also used for security officers on the U.S.S. Enterprise, which may be why so many redshirts died on away missions; they were ancillary security officers. Red uniforms were also worn by yeomen, who essentially helped with clerical work and didn’t have a rank. It’s worth noting that in the canon of “Star Trek,” engineers, yeomen, and security officers don’t have to attend Starfleet Academy to serve on board a starship. One can simply enlist. Those officers answer to the heads of their respective departments.
Those in blue, like Spock (Leonard Nimoy) and Dr. McCoy (DeForest Kelley), are in charge of scientific research and medicine. A lot of “Star Trek” is devoted to the sciences, so it makes sense that it would be an active and enormous part of any ship. The science/medical department is pretty self-explanatory.
One might note that Kirk occasionally wore a green tunic with a V-neck collar. The green uniform didn’t denote any unique department and seemed to be a regulation fashionable alternate for starship captains. If a captain was bored with their standard gold uniform, they were allowed — on casual Fridays? — to wear the green one.