The closet that Pete Buttigieg built for himself in the late 1990s and 2000s was a lot like the ones that other gay men of his age and ambition hid inside. He dated women, deepened his voice and furtively looked at MySpace and Friendster profiles of guys who had come out — all while wondering when it might be safe for him to do so too .

Chris Pappas, who was two years ahead of Mr. Buttigieg at Harvard and is now a Democratic congressman from New Hampshire, said he arrived at college “pretty much convinced that I couldn’t have a career or pursue politics as an L.G.B.T. individual.” Jonathan Darman , who was one class ahead of Mr. Buttigieg, remembered how people often reacted to a politician’s coming out then: “It wasn’t a story of love but of acknowledging illicit desire.” And Amit Paley, who graduated in Mr. Buttigieg’s class, recalled that “it was still a time where vocalizing anti-gay sentiments was not only common, but I think pretty accepted.”

The thought that 15 years later someone they might have shared a dorm or sat in a lecture hall with would become the first serious openly gay candidate for president of the United States never crossed their minds. But no one would have found the possibility more implausible than the young man everyone on campus knew as Peter.

Mr. Buttigieg, now the mayor of South Bend, Ind., struggled for a decade after leaving Harvard to overcome the fear that being gay was “a career death sentence,” as he put it in his memoir.